babylon.max.js 3.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376
  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 () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var MathTools = (function () {
  23. function MathTools() {
  24. }
  25. /**
  26. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  27. */
  28. MathTools.WithinEpsilon = function (a, b, epsilon) {
  29. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  30. var num = a - b;
  31. return -epsilon <= num && num <= epsilon;
  32. };
  33. /**
  34. * Returns a string : the upper case translation of the number i to hexadecimal.
  35. */
  36. MathTools.ToHex = function (i) {
  37. var str = i.toString(16);
  38. if (i <= 15) {
  39. return ("0" + str).toUpperCase();
  40. }
  41. return str.toUpperCase();
  42. };
  43. /**
  44. * Returns -1 if value is negative and +1 is value is positive.
  45. * Returns the value itself if it's equal to zero.
  46. */
  47. MathTools.Sign = function (value) {
  48. value = +value; // convert to a number
  49. if (value === 0 || isNaN(value))
  50. return value;
  51. return value > 0 ? 1 : -1;
  52. };
  53. /**
  54. * Returns the value itself if it's between min and max.
  55. * Returns min if the value is lower than min.
  56. * Returns max if the value is greater than max.
  57. */
  58. MathTools.Clamp = function (value, min, max) {
  59. if (min === void 0) { min = 0; }
  60. if (max === void 0) { max = 1; }
  61. return Math.min(max, Math.max(min, value));
  62. };
  63. return MathTools;
  64. }());
  65. BABYLON.MathTools = MathTools;
  66. var Color3 = (function () {
  67. /**
  68. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  69. */
  70. function Color3(r, g, b) {
  71. if (r === void 0) { r = 0; }
  72. if (g === void 0) { g = 0; }
  73. if (b === void 0) { b = 0; }
  74. this.r = r;
  75. this.g = g;
  76. this.b = b;
  77. }
  78. /**
  79. * Returns a string with the Color3 current values.
  80. */
  81. Color3.prototype.toString = function () {
  82. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  83. };
  84. /**
  85. * Returns the string "Color3".
  86. */
  87. Color3.prototype.getClassName = function () {
  88. return "Color3";
  89. };
  90. /**
  91. * Returns the Color3 hash code.
  92. */
  93. Color3.prototype.getHashCode = function () {
  94. var hash = this.r || 0;
  95. hash = (hash * 397) ^ (this.g || 0);
  96. hash = (hash * 397) ^ (this.b || 0);
  97. return hash;
  98. };
  99. // Operators
  100. /**
  101. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  102. * Returns the Color3.
  103. */
  104. Color3.prototype.toArray = function (array, index) {
  105. if (index === undefined) {
  106. index = 0;
  107. }
  108. array[index] = this.r;
  109. array[index + 1] = this.g;
  110. array[index + 2] = this.b;
  111. return this;
  112. };
  113. /**
  114. * Returns a new Color4 object from the current Color3 and the passed alpha.
  115. */
  116. Color3.prototype.toColor4 = function (alpha) {
  117. if (alpha === void 0) { alpha = 1; }
  118. return new Color4(this.r, this.g, this.b, alpha);
  119. };
  120. /**
  121. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  122. */
  123. Color3.prototype.asArray = function () {
  124. var result = [];
  125. this.toArray(result, 0);
  126. return result;
  127. };
  128. /**
  129. * Returns the luminance value (float).
  130. */
  131. Color3.prototype.toLuminance = function () {
  132. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  133. };
  134. /**
  135. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  136. * Returns this new object.
  137. */
  138. Color3.prototype.multiply = function (otherColor) {
  139. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  140. };
  141. /**
  142. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  143. * Returns the current Color3.
  144. */
  145. Color3.prototype.multiplyToRef = function (otherColor, result) {
  146. result.r = this.r * otherColor.r;
  147. result.g = this.g * otherColor.g;
  148. result.b = this.b * otherColor.b;
  149. return this;
  150. };
  151. /**
  152. * Boolean : True if the rgb values are equal to the passed ones.
  153. */
  154. Color3.prototype.equals = function (otherColor) {
  155. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  156. };
  157. /**
  158. * Boolean : True if the rgb values are equal to the passed ones.
  159. */
  160. Color3.prototype.equalsFloats = function (r, g, b) {
  161. return this.r === r && this.g === g && this.b === b;
  162. };
  163. /**
  164. * Multiplies in place each rgb value by scale.
  165. * Returns the updated Color3.
  166. */
  167. Color3.prototype.scale = function (scale) {
  168. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  169. };
  170. /**
  171. * Multiplies the rgb values by scale and stores the result into "result".
  172. * Returns the unmodified current Color3.
  173. */
  174. Color3.prototype.scaleToRef = function (scale, result) {
  175. result.r = this.r * scale;
  176. result.g = this.g * scale;
  177. result.b = this.b * scale;
  178. return this;
  179. };
  180. /**
  181. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  182. */
  183. Color3.prototype.add = function (otherColor) {
  184. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  185. };
  186. /**
  187. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  188. * Returns the unmodified current Color3.
  189. */
  190. Color3.prototype.addToRef = function (otherColor, result) {
  191. result.r = this.r + otherColor.r;
  192. result.g = this.g + otherColor.g;
  193. result.b = this.b + otherColor.b;
  194. return this;
  195. };
  196. /**
  197. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  198. */
  199. Color3.prototype.subtract = function (otherColor) {
  200. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  201. };
  202. /**
  203. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  204. * Returns the unmodified current Color3.
  205. */
  206. Color3.prototype.subtractToRef = function (otherColor, result) {
  207. result.r = this.r - otherColor.r;
  208. result.g = this.g - otherColor.g;
  209. result.b = this.b - otherColor.b;
  210. return this;
  211. };
  212. /**
  213. * Returns a new Color3 copied the current one.
  214. */
  215. Color3.prototype.clone = function () {
  216. return new Color3(this.r, this.g, this.b);
  217. };
  218. /**
  219. * Copies the rgb values from the source in the current Color3.
  220. * Returns the updated Color3.
  221. */
  222. Color3.prototype.copyFrom = function (source) {
  223. this.r = source.r;
  224. this.g = source.g;
  225. this.b = source.b;
  226. return this;
  227. };
  228. /**
  229. * Updates the Color3 rgb values from the passed floats.
  230. * Returns the Color3.
  231. */
  232. Color3.prototype.copyFromFloats = function (r, g, b) {
  233. this.r = r;
  234. this.g = g;
  235. this.b = b;
  236. return this;
  237. };
  238. /**
  239. * Updates the Color3 rgb values from the passed floats.
  240. * Returns the Color3.
  241. */
  242. Color3.prototype.set = function (r, g, b) {
  243. return this.copyFromFloats(r, g, b);
  244. };
  245. /**
  246. * Returns the Color3 hexadecimal code as a string.
  247. */
  248. Color3.prototype.toHexString = function () {
  249. var intR = (this.r * 255) | 0;
  250. var intG = (this.g * 255) | 0;
  251. var intB = (this.b * 255) | 0;
  252. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  253. };
  254. /**
  255. * Returns a new Color3 converted to linear space.
  256. */
  257. Color3.prototype.toLinearSpace = function () {
  258. var convertedColor = new Color3();
  259. this.toLinearSpaceToRef(convertedColor);
  260. return convertedColor;
  261. };
  262. /**
  263. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  264. * Returns the unmodified Color3.
  265. */
  266. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  267. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  268. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  269. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  270. return this;
  271. };
  272. /**
  273. * Returns a new Color3 converted to gamma space.
  274. */
  275. Color3.prototype.toGammaSpace = function () {
  276. var convertedColor = new Color3();
  277. this.toGammaSpaceToRef(convertedColor);
  278. return convertedColor;
  279. };
  280. /**
  281. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  282. * Returns the unmodified Color3.
  283. */
  284. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  285. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  286. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  287. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  288. return this;
  289. };
  290. // Statics
  291. /**
  292. * Creates a new Color3 from the string containing valid hexadecimal values.
  293. */
  294. Color3.FromHexString = function (hex) {
  295. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  296. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  297. return new Color3(0, 0, 0);
  298. }
  299. var r = parseInt(hex.substring(1, 3), 16);
  300. var g = parseInt(hex.substring(3, 5), 16);
  301. var b = parseInt(hex.substring(5, 7), 16);
  302. return Color3.FromInts(r, g, b);
  303. };
  304. /**
  305. * Creates a new Vector3 from the startind index of the passed array.
  306. */
  307. Color3.FromArray = function (array, offset) {
  308. if (offset === void 0) { offset = 0; }
  309. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  310. };
  311. /**
  312. * Creates a new Color3 from integer values ( < 256).
  313. */
  314. Color3.FromInts = function (r, g, b) {
  315. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  316. };
  317. /**
  318. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  319. */
  320. Color3.Lerp = function (start, end, amount) {
  321. var r = start.r + ((end.r - start.r) * amount);
  322. var g = start.g + ((end.g - start.g) * amount);
  323. var b = start.b + ((end.b - start.b) * amount);
  324. return new Color3(r, g, b);
  325. };
  326. Color3.Red = function () { return new Color3(1, 0, 0); };
  327. Color3.Green = function () { return new Color3(0, 1, 0); };
  328. Color3.Blue = function () { return new Color3(0, 0, 1); };
  329. Color3.Black = function () { return new Color3(0, 0, 0); };
  330. Color3.White = function () { return new Color3(1, 1, 1); };
  331. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  332. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  333. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  334. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  335. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  336. return Color3;
  337. }());
  338. BABYLON.Color3 = Color3;
  339. var Color4 = (function () {
  340. /**
  341. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  342. */
  343. function Color4(r, g, b, a) {
  344. this.r = r;
  345. this.g = g;
  346. this.b = b;
  347. this.a = a;
  348. }
  349. // Operators
  350. /**
  351. * Adds in place the passed Color4 values to the current Color4.
  352. * Returns the updated Color4.
  353. */
  354. Color4.prototype.addInPlace = function (right) {
  355. this.r += right.r;
  356. this.g += right.g;
  357. this.b += right.b;
  358. this.a += right.a;
  359. return this;
  360. };
  361. /**
  362. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  363. */
  364. Color4.prototype.asArray = function () {
  365. var result = [];
  366. this.toArray(result, 0);
  367. return result;
  368. };
  369. /**
  370. * Stores from the starting index in the passed array the Color4 successive values.
  371. * Returns the Color4.
  372. */
  373. Color4.prototype.toArray = function (array, index) {
  374. if (index === undefined) {
  375. index = 0;
  376. }
  377. array[index] = this.r;
  378. array[index + 1] = this.g;
  379. array[index + 2] = this.b;
  380. array[index + 3] = this.a;
  381. return this;
  382. };
  383. /**
  384. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  385. */
  386. Color4.prototype.add = function (right) {
  387. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  388. };
  389. /**
  390. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  391. */
  392. Color4.prototype.subtract = function (right) {
  393. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  394. };
  395. /**
  396. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  397. * Returns the Color4.
  398. */
  399. Color4.prototype.subtractToRef = function (right, result) {
  400. result.r = this.r - right.r;
  401. result.g = this.g - right.g;
  402. result.b = this.b - right.b;
  403. result.a = this.a - right.a;
  404. return this;
  405. };
  406. /**
  407. * Creates a new Color4 with the current Color4 values multiplied by scale.
  408. */
  409. Color4.prototype.scale = function (scale) {
  410. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  411. };
  412. /**
  413. * Multiplies the current Color4 values by scale and stores the result in "result".
  414. * Returns the Color4.
  415. */
  416. Color4.prototype.scaleToRef = function (scale, result) {
  417. result.r = this.r * scale;
  418. result.g = this.g * scale;
  419. result.b = this.b * scale;
  420. result.a = this.a * scale;
  421. return this;
  422. };
  423. /**
  424. * Multipy an RGBA Color4 value by another and return a new Color4 object
  425. * @param color The Color4 (RGBA) value to multiply by
  426. * @returns A new Color4.
  427. */
  428. Color4.prototype.multiply = function (color) {
  429. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  430. };
  431. /**
  432. * Multipy an RGBA Color4 value by another and push the result in a reference value
  433. * @param color The Color4 (RGBA) value to multiply by
  434. * @param result The Color4 (RGBA) to fill the result in
  435. * @returns the result Color4.
  436. */
  437. Color4.prototype.multiplyToRef = function (color, result) {
  438. result.r = this.r * color.r;
  439. result.g = this.g * color.g;
  440. result.b = this.b * color.b;
  441. result.a = this.a * color.a;
  442. return result;
  443. };
  444. /**
  445. * Returns a string with the Color4 values.
  446. */
  447. Color4.prototype.toString = function () {
  448. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  449. };
  450. /**
  451. * Returns the string "Color4"
  452. */
  453. Color4.prototype.getClassName = function () {
  454. return "Color4";
  455. };
  456. /**
  457. * Return the Color4 hash code as a number.
  458. */
  459. Color4.prototype.getHashCode = function () {
  460. var hash = this.r || 0;
  461. hash = (hash * 397) ^ (this.g || 0);
  462. hash = (hash * 397) ^ (this.b || 0);
  463. hash = (hash * 397) ^ (this.a || 0);
  464. return hash;
  465. };
  466. /**
  467. * Creates a new Color4 copied from the current one.
  468. */
  469. Color4.prototype.clone = function () {
  470. return new Color4(this.r, this.g, this.b, this.a);
  471. };
  472. /**
  473. * Copies the passed Color4 values into the current one.
  474. * Returns the updated Color4.
  475. */
  476. Color4.prototype.copyFrom = function (source) {
  477. this.r = source.r;
  478. this.g = source.g;
  479. this.b = source.b;
  480. this.a = source.a;
  481. return this;
  482. };
  483. /**
  484. * Copies the passed float values into the current one.
  485. * Returns the updated Color4.
  486. */
  487. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  488. this.r = r;
  489. this.g = g;
  490. this.b = b;
  491. this.a = a;
  492. return this;
  493. };
  494. /**
  495. * Copies the passed float values into the current one.
  496. * Returns the updated Color4.
  497. */
  498. Color4.prototype.set = function (r, g, b, a) {
  499. return this.copyFromFloats(r, g, b, a);
  500. };
  501. /**
  502. * Returns a string containing the hexadecimal Color4 code.
  503. */
  504. Color4.prototype.toHexString = function () {
  505. var intR = (this.r * 255) | 0;
  506. var intG = (this.g * 255) | 0;
  507. var intB = (this.b * 255) | 0;
  508. var intA = (this.a * 255) | 0;
  509. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  510. };
  511. // Statics
  512. /**
  513. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  514. */
  515. Color4.FromHexString = function (hex) {
  516. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  517. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  518. return new Color4(0.0, 0.0, 0.0, 0.0);
  519. }
  520. var r = parseInt(hex.substring(1, 3), 16);
  521. var g = parseInt(hex.substring(3, 5), 16);
  522. var b = parseInt(hex.substring(5, 7), 16);
  523. var a = parseInt(hex.substring(7, 9), 16);
  524. return Color4.FromInts(r, g, b, a);
  525. };
  526. /**
  527. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  528. */
  529. Color4.Lerp = function (left, right, amount) {
  530. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  531. Color4.LerpToRef(left, right, amount, result);
  532. return result;
  533. };
  534. /**
  535. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  536. */
  537. Color4.LerpToRef = function (left, right, amount, result) {
  538. result.r = left.r + (right.r - left.r) * amount;
  539. result.g = left.g + (right.g - left.g) * amount;
  540. result.b = left.b + (right.b - left.b) * amount;
  541. result.a = left.a + (right.a - left.a) * amount;
  542. };
  543. /**
  544. * Creates a new Color4 from the starting index element of the passed array.
  545. */
  546. Color4.FromArray = function (array, offset) {
  547. if (offset === void 0) { offset = 0; }
  548. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  549. };
  550. /**
  551. * Creates a new Color4 from the passed integers ( < 256 ).
  552. */
  553. Color4.FromInts = function (r, g, b, a) {
  554. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  555. };
  556. Color4.CheckColors4 = function (colors, count) {
  557. // Check if color3 was used
  558. if (colors.length === count * 3) {
  559. var colors4 = [];
  560. for (var index = 0; index < colors.length; index += 3) {
  561. var newIndex = (index / 3) * 4;
  562. colors4[newIndex] = colors[index];
  563. colors4[newIndex + 1] = colors[index + 1];
  564. colors4[newIndex + 2] = colors[index + 2];
  565. colors4[newIndex + 3] = 1.0;
  566. }
  567. return colors4;
  568. }
  569. return colors;
  570. };
  571. return Color4;
  572. }());
  573. BABYLON.Color4 = Color4;
  574. var Vector2 = (function () {
  575. /**
  576. * Creates a new Vector2 from the passed x and y coordinates.
  577. */
  578. function Vector2(x, y) {
  579. this.x = x;
  580. this.y = y;
  581. }
  582. /**
  583. * Returns a string with the Vector2 coordinates.
  584. */
  585. Vector2.prototype.toString = function () {
  586. return "{X: " + this.x + " Y:" + this.y + "}";
  587. };
  588. /**
  589. * Returns the string "Vector2"
  590. */
  591. Vector2.prototype.getClassName = function () {
  592. return "Vector2";
  593. };
  594. /**
  595. * Returns the Vector2 hash code as a number.
  596. */
  597. Vector2.prototype.getHashCode = function () {
  598. var hash = this.x || 0;
  599. hash = (hash * 397) ^ (this.y || 0);
  600. return hash;
  601. };
  602. // Operators
  603. /**
  604. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  605. * Returns the Vector2.
  606. */
  607. Vector2.prototype.toArray = function (array, index) {
  608. if (index === void 0) { index = 0; }
  609. array[index] = this.x;
  610. array[index + 1] = this.y;
  611. return this;
  612. };
  613. /**
  614. * Returns a new array with 2 elements : the Vector2 coordinates.
  615. */
  616. Vector2.prototype.asArray = function () {
  617. var result = [];
  618. this.toArray(result, 0);
  619. return result;
  620. };
  621. /**
  622. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  623. * Returns the updated Vector2.
  624. */
  625. Vector2.prototype.copyFrom = function (source) {
  626. this.x = source.x;
  627. this.y = source.y;
  628. return this;
  629. };
  630. /**
  631. * Sets the Vector2 coordinates with the passed floats.
  632. * Returns the updated Vector2.
  633. */
  634. Vector2.prototype.copyFromFloats = function (x, y) {
  635. this.x = x;
  636. this.y = y;
  637. return this;
  638. };
  639. /**
  640. * Sets the Vector2 coordinates with the passed floats.
  641. * Returns the updated Vector2.
  642. */
  643. Vector2.prototype.set = function (x, y) {
  644. return this.copyFromFloats(x, y);
  645. };
  646. /**
  647. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  648. */
  649. Vector2.prototype.add = function (otherVector) {
  650. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  651. };
  652. /**
  653. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  654. * Returns the Vector2.
  655. */
  656. Vector2.prototype.addToRef = function (otherVector, result) {
  657. result.x = this.x + otherVector.x;
  658. result.y = this.y + otherVector.y;
  659. return this;
  660. };
  661. /**
  662. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  663. * Returns the updated Vector2.
  664. */
  665. Vector2.prototype.addInPlace = function (otherVector) {
  666. this.x += otherVector.x;
  667. this.y += otherVector.y;
  668. return this;
  669. };
  670. /**
  671. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  672. */
  673. Vector2.prototype.addVector3 = function (otherVector) {
  674. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  675. };
  676. /**
  677. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  678. */
  679. Vector2.prototype.subtract = function (otherVector) {
  680. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  681. };
  682. /**
  683. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  684. * Returns the Vector2.
  685. */
  686. Vector2.prototype.subtractToRef = function (otherVector, result) {
  687. result.x = this.x - otherVector.x;
  688. result.y = this.y - otherVector.y;
  689. return this;
  690. };
  691. /**
  692. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  693. * Returns the updated Vector2.
  694. */
  695. Vector2.prototype.subtractInPlace = function (otherVector) {
  696. this.x -= otherVector.x;
  697. this.y -= otherVector.y;
  698. return this;
  699. };
  700. /**
  701. * Multiplies in place the current Vector2 coordinates by the passed ones.
  702. * Returns the updated Vector2.
  703. */
  704. Vector2.prototype.multiplyInPlace = function (otherVector) {
  705. this.x *= otherVector.x;
  706. this.y *= otherVector.y;
  707. return this;
  708. };
  709. /**
  710. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  711. */
  712. Vector2.prototype.multiply = function (otherVector) {
  713. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  714. };
  715. /**
  716. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  717. * Returns the Vector2.
  718. */
  719. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  720. result.x = this.x * otherVector.x;
  721. result.y = this.y * otherVector.y;
  722. return this;
  723. };
  724. /**
  725. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  726. */
  727. Vector2.prototype.multiplyByFloats = function (x, y) {
  728. return new Vector2(this.x * x, this.y * y);
  729. };
  730. /**
  731. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  732. */
  733. Vector2.prototype.divide = function (otherVector) {
  734. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  735. };
  736. /**
  737. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  738. * Returns the Vector2.
  739. */
  740. Vector2.prototype.divideToRef = function (otherVector, result) {
  741. result.x = this.x / otherVector.x;
  742. result.y = this.y / otherVector.y;
  743. return this;
  744. };
  745. /**
  746. * Returns a new Vector2 with current Vector2 negated coordinates.
  747. */
  748. Vector2.prototype.negate = function () {
  749. return new Vector2(-this.x, -this.y);
  750. };
  751. /**
  752. * Multiply the Vector2 coordinates by scale.
  753. * Returns the updated Vector2.
  754. */
  755. Vector2.prototype.scaleInPlace = function (scale) {
  756. this.x *= scale;
  757. this.y *= scale;
  758. return this;
  759. };
  760. /**
  761. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  762. */
  763. Vector2.prototype.scale = function (scale) {
  764. return new Vector2(this.x * scale, this.y * scale);
  765. };
  766. /**
  767. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  768. */
  769. Vector2.prototype.equals = function (otherVector) {
  770. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  771. };
  772. /**
  773. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  774. */
  775. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  776. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  777. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  778. };
  779. // Properties
  780. /**
  781. * Returns the vector length (float).
  782. */
  783. Vector2.prototype.length = function () {
  784. return Math.sqrt(this.x * this.x + this.y * this.y);
  785. };
  786. /**
  787. * Returns the vector squared length (float);
  788. */
  789. Vector2.prototype.lengthSquared = function () {
  790. return (this.x * this.x + this.y * this.y);
  791. };
  792. // Methods
  793. /**
  794. * Normalize the vector.
  795. * Returns the updated Vector2.
  796. */
  797. Vector2.prototype.normalize = function () {
  798. var len = this.length();
  799. if (len === 0)
  800. return this;
  801. var num = 1.0 / len;
  802. this.x *= num;
  803. this.y *= num;
  804. return this;
  805. };
  806. /**
  807. * Returns a new Vector2 copied from the Vector2.
  808. */
  809. Vector2.prototype.clone = function () {
  810. return new Vector2(this.x, this.y);
  811. };
  812. // Statics
  813. /**
  814. * Returns a new Vector2(0, 0)
  815. */
  816. Vector2.Zero = function () {
  817. return new Vector2(0, 0);
  818. };
  819. /**
  820. * Returns a new Vector2 set from the passed index element of the passed array or Float32Array.
  821. */
  822. Vector2.FromArray = function (array, offset) {
  823. if (offset === void 0) { offset = 0; }
  824. return new Vector2(array[offset], array[offset + 1]);
  825. };
  826. /**
  827. * Sets "result" from the passed index element of the passed array or Float32Array.
  828. * Returns the Vector2.
  829. */
  830. Vector2.FromArrayToRef = function (array, offset, result) {
  831. result.x = array[offset];
  832. result.y = array[offset + 1];
  833. };
  834. /**
  835. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  836. */
  837. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  838. var squared = amount * amount;
  839. var cubed = amount * squared;
  840. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  841. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  842. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  843. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  844. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  845. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  846. return new Vector2(x, y);
  847. };
  848. /**
  849. * 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".
  850. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  851. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  852. */
  853. Vector2.Clamp = function (value, min, max) {
  854. var x = value.x;
  855. x = (x > max.x) ? max.x : x;
  856. x = (x < min.x) ? min.x : x;
  857. var y = value.y;
  858. y = (y > max.y) ? max.y : y;
  859. y = (y < min.y) ? min.y : y;
  860. return new Vector2(x, y);
  861. };
  862. /**
  863. * Returns a new Vecto2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  864. */
  865. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  866. var squared = amount * amount;
  867. var cubed = amount * squared;
  868. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  869. var part2 = (-2.0 * cubed) + (3.0 * squared);
  870. var part3 = (cubed - (2.0 * squared)) + amount;
  871. var part4 = cubed - squared;
  872. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  873. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  874. return new Vector2(x, y);
  875. };
  876. /**
  877. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  878. */
  879. Vector2.Lerp = function (start, end, amount) {
  880. var x = start.x + ((end.x - start.x) * amount);
  881. var y = start.y + ((end.y - start.y) * amount);
  882. return new Vector2(x, y);
  883. };
  884. /**
  885. * Returns the dot product (float) of the vector "left" and the vector "right".
  886. */
  887. Vector2.Dot = function (left, right) {
  888. return left.x * right.x + left.y * right.y;
  889. };
  890. /**
  891. * Returns a new Vector2 equal to the normalized passed vector.
  892. */
  893. Vector2.Normalize = function (vector) {
  894. var newVector = vector.clone();
  895. newVector.normalize();
  896. return newVector;
  897. };
  898. /**
  899. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  900. */
  901. Vector2.Minimize = function (left, right) {
  902. var x = (left.x < right.x) ? left.x : right.x;
  903. var y = (left.y < right.y) ? left.y : right.y;
  904. return new Vector2(x, y);
  905. };
  906. /**
  907. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  908. */
  909. Vector2.Maximize = function (left, right) {
  910. var x = (left.x > right.x) ? left.x : right.x;
  911. var y = (left.y > right.y) ? left.y : right.y;
  912. return new Vector2(x, y);
  913. };
  914. /**
  915. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  916. */
  917. Vector2.Transform = function (vector, transformation) {
  918. var r = Vector2.Zero();
  919. Vector2.TransformToRef(vector, transformation, r);
  920. return r;
  921. };
  922. /**
  923. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  924. */
  925. Vector2.TransformToRef = function (vector, transformation, result) {
  926. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  927. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  928. result.x = x;
  929. result.y = y;
  930. };
  931. /**
  932. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  933. */
  934. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  935. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  936. var sign = a < 0 ? -1 : 1;
  937. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  938. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  939. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  940. };
  941. /**
  942. * Returns the distance (float) between the vectors "value1" and "value2".
  943. */
  944. Vector2.Distance = function (value1, value2) {
  945. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  946. };
  947. /**
  948. * Returns the squared distance (float) between the vectors "value1" and "value2".
  949. */
  950. Vector2.DistanceSquared = function (value1, value2) {
  951. var x = value1.x - value2.x;
  952. var y = value1.y - value2.y;
  953. return (x * x) + (y * y);
  954. };
  955. /**
  956. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  957. */
  958. Vector2.Center = function (value1, value2) {
  959. var center = value1.add(value2);
  960. center.scaleInPlace(0.5);
  961. return center;
  962. };
  963. /**
  964. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  965. */
  966. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  967. var l2 = Vector2.DistanceSquared(segA, segB);
  968. if (l2 === 0.0) {
  969. return Vector2.Distance(p, segA);
  970. }
  971. var v = segB.subtract(segA);
  972. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  973. var proj = segA.add(v.multiplyByFloats(t, t));
  974. return Vector2.Distance(p, proj);
  975. };
  976. return Vector2;
  977. }());
  978. BABYLON.Vector2 = Vector2;
  979. var Vector3 = (function () {
  980. /**
  981. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  982. * A Vector3 is the main object used in 3D geometry.
  983. * It can represent etiher the coordinates of a point the space, either a direction.
  984. */
  985. function Vector3(x, y, z) {
  986. this.x = x;
  987. this.y = y;
  988. this.z = z;
  989. }
  990. /**
  991. * Returns a string with the Vector3 coordinates.
  992. */
  993. Vector3.prototype.toString = function () {
  994. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  995. };
  996. /**
  997. * Returns the string "Vector3"
  998. */
  999. Vector3.prototype.getClassName = function () {
  1000. return "Vector3";
  1001. };
  1002. /**
  1003. * Returns the Vector hash code.
  1004. */
  1005. Vector3.prototype.getHashCode = function () {
  1006. var hash = this.x || 0;
  1007. hash = (hash * 397) ^ (this.y || 0);
  1008. hash = (hash * 397) ^ (this.z || 0);
  1009. return hash;
  1010. };
  1011. // Operators
  1012. /**
  1013. * Returns a new array with three elements : the coordinates the Vector3.
  1014. */
  1015. Vector3.prototype.asArray = function () {
  1016. var result = [];
  1017. this.toArray(result, 0);
  1018. return result;
  1019. };
  1020. /**
  1021. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1022. * Returns the Vector3.
  1023. */
  1024. Vector3.prototype.toArray = function (array, index) {
  1025. if (index === void 0) { index = 0; }
  1026. array[index] = this.x;
  1027. array[index + 1] = this.y;
  1028. array[index + 2] = this.z;
  1029. return this;
  1030. };
  1031. /**
  1032. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1033. */
  1034. Vector3.prototype.toQuaternion = function () {
  1035. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1036. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1037. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1038. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1039. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1040. var cosy = Math.cos(this.y * 0.5);
  1041. var siny = Math.sin(this.y * 0.5);
  1042. result.x = coszMinusx * siny;
  1043. result.y = -sinzMinusx * siny;
  1044. result.z = sinxPlusz * cosy;
  1045. result.w = cosxPlusz * cosy;
  1046. return result;
  1047. };
  1048. /**
  1049. * Adds the passed vector to the current Vector3.
  1050. * Returns the updated Vector3.
  1051. */
  1052. Vector3.prototype.addInPlace = function (otherVector) {
  1053. this.x += otherVector.x;
  1054. this.y += otherVector.y;
  1055. this.z += otherVector.z;
  1056. return this;
  1057. };
  1058. /**
  1059. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1060. */
  1061. Vector3.prototype.add = function (otherVector) {
  1062. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1063. };
  1064. /**
  1065. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1066. * Returns the current Vector3.
  1067. */
  1068. Vector3.prototype.addToRef = function (otherVector, result) {
  1069. result.x = this.x + otherVector.x;
  1070. result.y = this.y + otherVector.y;
  1071. result.z = this.z + otherVector.z;
  1072. return this;
  1073. };
  1074. /**
  1075. * Subtract the passed vector from the current Vector3.
  1076. * Returns the updated Vector3.
  1077. */
  1078. Vector3.prototype.subtractInPlace = function (otherVector) {
  1079. this.x -= otherVector.x;
  1080. this.y -= otherVector.y;
  1081. this.z -= otherVector.z;
  1082. return this;
  1083. };
  1084. /**
  1085. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1086. */
  1087. Vector3.prototype.subtract = function (otherVector) {
  1088. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1089. };
  1090. /**
  1091. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1092. * Returns the current Vector3.
  1093. */
  1094. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1095. result.x = this.x - otherVector.x;
  1096. result.y = this.y - otherVector.y;
  1097. result.z = this.z - otherVector.z;
  1098. return this;
  1099. };
  1100. /**
  1101. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1102. */
  1103. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1104. return new Vector3(this.x - x, this.y - y, this.z - z);
  1105. };
  1106. /**
  1107. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1108. * Returns the current Vector3.
  1109. */
  1110. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1111. result.x = this.x - x;
  1112. result.y = this.y - y;
  1113. result.z = this.z - z;
  1114. return this;
  1115. };
  1116. /**
  1117. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1118. */
  1119. Vector3.prototype.negate = function () {
  1120. return new Vector3(-this.x, -this.y, -this.z);
  1121. };
  1122. /**
  1123. * Multiplies the Vector3 coordinates by the float "scale".
  1124. * Returns the updated Vector3.
  1125. */
  1126. Vector3.prototype.scaleInPlace = function (scale) {
  1127. this.x *= scale;
  1128. this.y *= scale;
  1129. this.z *= scale;
  1130. return this;
  1131. };
  1132. /**
  1133. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1134. */
  1135. Vector3.prototype.scale = function (scale) {
  1136. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1137. };
  1138. /**
  1139. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1140. * Returns the current Vector3.
  1141. */
  1142. Vector3.prototype.scaleToRef = function (scale, result) {
  1143. result.x = this.x * scale;
  1144. result.y = this.y * scale;
  1145. result.z = this.z * scale;
  1146. return this;
  1147. };
  1148. /**
  1149. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1150. */
  1151. Vector3.prototype.equals = function (otherVector) {
  1152. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1153. };
  1154. /**
  1155. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1156. */
  1157. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1158. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1159. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1160. };
  1161. /**
  1162. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1163. */
  1164. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1165. return this.x === x && this.y === y && this.z === z;
  1166. };
  1167. /**
  1168. * Muliplies the current Vector3 coordinates by the passed ones.
  1169. * Returns the updated Vector3.
  1170. */
  1171. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1172. this.x *= otherVector.x;
  1173. this.y *= otherVector.y;
  1174. this.z *= otherVector.z;
  1175. return this;
  1176. };
  1177. /**
  1178. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1179. */
  1180. Vector3.prototype.multiply = function (otherVector) {
  1181. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1182. };
  1183. /**
  1184. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1185. * Returns the current Vector3.
  1186. */
  1187. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1188. result.x = this.x * otherVector.x;
  1189. result.y = this.y * otherVector.y;
  1190. result.z = this.z * otherVector.z;
  1191. return this;
  1192. };
  1193. /**
  1194. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1195. */
  1196. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1197. return new Vector3(this.x * x, this.y * y, this.z * z);
  1198. };
  1199. /**
  1200. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1201. */
  1202. Vector3.prototype.divide = function (otherVector) {
  1203. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1204. };
  1205. /**
  1206. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1207. * Returns the current Vector3.
  1208. */
  1209. Vector3.prototype.divideToRef = function (otherVector, result) {
  1210. result.x = this.x / otherVector.x;
  1211. result.y = this.y / otherVector.y;
  1212. result.z = this.z / otherVector.z;
  1213. return this;
  1214. };
  1215. /**
  1216. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1217. * Returns the updated Vector3.
  1218. */
  1219. Vector3.prototype.MinimizeInPlace = function (other) {
  1220. if (other.x < this.x)
  1221. this.x = other.x;
  1222. if (other.y < this.y)
  1223. this.y = other.y;
  1224. if (other.z < this.z)
  1225. this.z = other.z;
  1226. return this;
  1227. };
  1228. /**
  1229. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1230. * Returns the updated Vector3.
  1231. */
  1232. Vector3.prototype.MaximizeInPlace = function (other) {
  1233. if (other.x > this.x)
  1234. this.x = other.x;
  1235. if (other.y > this.y)
  1236. this.y = other.y;
  1237. if (other.z > this.z)
  1238. this.z = other.z;
  1239. return this;
  1240. };
  1241. // Properties
  1242. /**
  1243. * Returns the length of the Vector3 (float).
  1244. */
  1245. Vector3.prototype.length = function () {
  1246. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1247. };
  1248. /**
  1249. * Returns the squared length of the Vector3 (float).
  1250. */
  1251. Vector3.prototype.lengthSquared = function () {
  1252. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1253. };
  1254. // Methods
  1255. /**
  1256. * Normalize the current Vector3.
  1257. * Returns the updated Vector3.
  1258. */
  1259. Vector3.prototype.normalize = function () {
  1260. var len = this.length();
  1261. if (len === 0 || len === 1.0)
  1262. return this;
  1263. var num = 1.0 / len;
  1264. this.x *= num;
  1265. this.y *= num;
  1266. this.z *= num;
  1267. return this;
  1268. };
  1269. /**
  1270. * Returns a new Vector3 copied from the current Vector3.
  1271. */
  1272. Vector3.prototype.clone = function () {
  1273. return new Vector3(this.x, this.y, this.z);
  1274. };
  1275. /**
  1276. * Copies the passed vector coordinates to the current Vector3 ones.
  1277. * Returns the updated Vector3.
  1278. */
  1279. Vector3.prototype.copyFrom = function (source) {
  1280. this.x = source.x;
  1281. this.y = source.y;
  1282. this.z = source.z;
  1283. return this;
  1284. };
  1285. /**
  1286. * Copies the passed floats to the current Vector3 coordinates.
  1287. * Returns the updated Vector3.
  1288. */
  1289. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1290. this.x = x;
  1291. this.y = y;
  1292. this.z = z;
  1293. return this;
  1294. };
  1295. /**
  1296. * Copies the passed floats to the current Vector3 coordinates.
  1297. * Returns the updated Vector3.
  1298. */
  1299. Vector3.prototype.set = function (x, y, z) {
  1300. return this.copyFromFloats(x, y, z);
  1301. };
  1302. // Statics
  1303. /**
  1304. *
  1305. */
  1306. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1307. var d0 = Vector3.Dot(vector0, axis) - size;
  1308. var d1 = Vector3.Dot(vector1, axis) - size;
  1309. var s = d0 / (d0 - d1);
  1310. return s;
  1311. };
  1312. /**
  1313. * Returns a new Vector3 set from the index "offset" of the passed array or Float32Array.
  1314. */
  1315. Vector3.FromArray = function (array, offset) {
  1316. if (!offset) {
  1317. offset = 0;
  1318. }
  1319. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1320. };
  1321. /**
  1322. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1323. */
  1324. Vector3.FromFloatArray = function (array, offset) {
  1325. if (!offset) {
  1326. offset = 0;
  1327. }
  1328. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1329. };
  1330. /**
  1331. * Sets the passed vector "result" with the element values from the index "offset" of the passed array or Float32Array.
  1332. */
  1333. Vector3.FromArrayToRef = function (array, offset, result) {
  1334. result.x = array[offset];
  1335. result.y = array[offset + 1];
  1336. result.z = array[offset + 2];
  1337. };
  1338. /**
  1339. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1340. */
  1341. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1342. result.x = array[offset];
  1343. result.y = array[offset + 1];
  1344. result.z = array[offset + 2];
  1345. };
  1346. /**
  1347. * Sets the passed vector "result" with the passed floats.
  1348. */
  1349. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1350. result.x = x;
  1351. result.y = y;
  1352. result.z = z;
  1353. };
  1354. /**
  1355. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1356. */
  1357. Vector3.Zero = function () {
  1358. return new Vector3(0.0, 0.0, 0.0);
  1359. };
  1360. /**
  1361. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1362. */
  1363. Vector3.Up = function () {
  1364. return new Vector3(0.0, 1.0, 0.0);
  1365. };
  1366. /**
  1367. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1368. */
  1369. Vector3.Forward = function () {
  1370. return new Vector3(0.0, 0.0, 1.0);
  1371. };
  1372. /**
  1373. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1374. */
  1375. Vector3.Right = function () {
  1376. return new Vector3(1.0, 0.0, 0.0);
  1377. };
  1378. /**
  1379. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1380. */
  1381. Vector3.Left = function () {
  1382. return new Vector3(-1.0, 0.0, 0.0);
  1383. };
  1384. /**
  1385. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1386. * This method computes tranformed coordinates only, not transformed direction vectors.
  1387. */
  1388. Vector3.TransformCoordinates = function (vector, transformation) {
  1389. var result = Vector3.Zero();
  1390. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1391. return result;
  1392. };
  1393. /**
  1394. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1395. * This method computes tranformed coordinates only, not transformed direction vectors.
  1396. */
  1397. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1398. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1399. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1400. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1401. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1402. result.x = x / w;
  1403. result.y = y / w;
  1404. result.z = z / w;
  1405. };
  1406. /**
  1407. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1408. * This method computes tranformed coordinates only, not transformed direction vectors.
  1409. */
  1410. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1411. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1412. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1413. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1414. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1415. result.x = rx / rw;
  1416. result.y = ry / rw;
  1417. result.z = rz / rw;
  1418. };
  1419. /**
  1420. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1421. * This methods computes transformed normalized direction vectors only.
  1422. */
  1423. Vector3.TransformNormal = function (vector, transformation) {
  1424. var result = Vector3.Zero();
  1425. Vector3.TransformNormalToRef(vector, transformation, result);
  1426. return result;
  1427. };
  1428. /**
  1429. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1430. * This methods computes transformed normalized direction vectors only.
  1431. */
  1432. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1433. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1434. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1435. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1436. result.x = x;
  1437. result.y = y;
  1438. result.z = z;
  1439. };
  1440. /**
  1441. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1442. * This methods computes transformed normalized direction vectors only.
  1443. */
  1444. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1445. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1446. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1447. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1448. };
  1449. /**
  1450. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1451. */
  1452. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1453. var squared = amount * amount;
  1454. var cubed = amount * squared;
  1455. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1456. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1457. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1458. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1459. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1460. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1461. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1462. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1463. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1464. return new Vector3(x, y, z);
  1465. };
  1466. /**
  1467. * 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".
  1468. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1469. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1470. */
  1471. Vector3.Clamp = function (value, min, max) {
  1472. var x = value.x;
  1473. x = (x > max.x) ? max.x : x;
  1474. x = (x < min.x) ? min.x : x;
  1475. var y = value.y;
  1476. y = (y > max.y) ? max.y : y;
  1477. y = (y < min.y) ? min.y : y;
  1478. var z = value.z;
  1479. z = (z > max.z) ? max.z : z;
  1480. z = (z < min.z) ? min.z : z;
  1481. return new Vector3(x, y, z);
  1482. };
  1483. /**
  1484. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1485. */
  1486. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1487. var squared = amount * amount;
  1488. var cubed = amount * squared;
  1489. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1490. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1491. var part3 = (cubed - (2.0 * squared)) + amount;
  1492. var part4 = cubed - squared;
  1493. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1494. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1495. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1496. return new Vector3(x, y, z);
  1497. };
  1498. /**
  1499. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1500. */
  1501. Vector3.Lerp = function (start, end, amount) {
  1502. var result = new Vector3(0, 0, 0);
  1503. Vector3.LerpToRef(start, end, amount, result);
  1504. return result;
  1505. };
  1506. /**
  1507. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1508. */
  1509. Vector3.LerpToRef = function (start, end, amount, result) {
  1510. result.x = start.x + ((end.x - start.x) * amount);
  1511. result.y = start.y + ((end.y - start.y) * amount);
  1512. result.z = start.z + ((end.z - start.z) * amount);
  1513. };
  1514. /**
  1515. * Returns the dot product (float) between the vectors "left" and "right".
  1516. */
  1517. Vector3.Dot = function (left, right) {
  1518. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1519. };
  1520. /**
  1521. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1522. * The cross product is then orthogonal to both "left" and "right".
  1523. */
  1524. Vector3.Cross = function (left, right) {
  1525. var result = Vector3.Zero();
  1526. Vector3.CrossToRef(left, right, result);
  1527. return result;
  1528. };
  1529. /**
  1530. * Sets the passed vector "result" with the cross product of "left" and "right".
  1531. * The cross product is then orthogonal to both "left" and "right".
  1532. */
  1533. Vector3.CrossToRef = function (left, right, result) {
  1534. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1535. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1536. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1537. result.copyFrom(MathTmp.Vector3[0]);
  1538. };
  1539. /**
  1540. * Returns a new Vector3 as the normalization of the passed vector.
  1541. */
  1542. Vector3.Normalize = function (vector) {
  1543. var result = Vector3.Zero();
  1544. Vector3.NormalizeToRef(vector, result);
  1545. return result;
  1546. };
  1547. /**
  1548. * Sets the passed vector "result" with the normalization of the passed first vector.
  1549. */
  1550. Vector3.NormalizeToRef = function (vector, result) {
  1551. result.copyFrom(vector);
  1552. result.normalize();
  1553. };
  1554. Vector3.Project = function (vector, world, transform, viewport) {
  1555. var cw = viewport.width;
  1556. var ch = viewport.height;
  1557. var cx = viewport.x;
  1558. var cy = viewport.y;
  1559. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1560. 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);
  1561. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1562. world.multiplyToRef(transform, matrix);
  1563. matrix.multiplyToRef(viewportMatrix, matrix);
  1564. return Vector3.TransformCoordinates(vector, matrix);
  1565. };
  1566. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1567. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1568. world.multiplyToRef(transform, matrix);
  1569. matrix.invert();
  1570. source.x = source.x / viewportWidth * 2 - 1;
  1571. source.y = -(source.y / viewportHeight * 2 - 1);
  1572. var vector = Vector3.TransformCoordinates(source, matrix);
  1573. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1574. if (MathTools.WithinEpsilon(num, 1.0)) {
  1575. vector = vector.scale(1.0 / num);
  1576. }
  1577. return vector;
  1578. };
  1579. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1580. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1581. world.multiplyToRef(view, matrix);
  1582. matrix.multiplyToRef(projection, matrix);
  1583. matrix.invert();
  1584. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1585. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1586. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1587. if (MathTools.WithinEpsilon(num, 1.0)) {
  1588. vector = vector.scale(1.0 / num);
  1589. }
  1590. return vector;
  1591. };
  1592. Vector3.Minimize = function (left, right) {
  1593. var min = left.clone();
  1594. min.MinimizeInPlace(right);
  1595. return min;
  1596. };
  1597. Vector3.Maximize = function (left, right) {
  1598. var max = left.clone();
  1599. max.MaximizeInPlace(right);
  1600. return max;
  1601. };
  1602. /**
  1603. * Returns the distance (float) between the vectors "value1" and "value2".
  1604. */
  1605. Vector3.Distance = function (value1, value2) {
  1606. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1607. };
  1608. /**
  1609. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1610. */
  1611. Vector3.DistanceSquared = function (value1, value2) {
  1612. var x = value1.x - value2.x;
  1613. var y = value1.y - value2.y;
  1614. var z = value1.z - value2.z;
  1615. return (x * x) + (y * y) + (z * z);
  1616. };
  1617. /**
  1618. * Returns a new Vector3 located at the center between "value1" and "value2".
  1619. */
  1620. Vector3.Center = function (value1, value2) {
  1621. var center = value1.add(value2);
  1622. center.scaleInPlace(0.5);
  1623. return center;
  1624. };
  1625. /**
  1626. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1627. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1628. * to something in order to rotate it from its local system to the given target system.
  1629. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1630. * Returns a new Vector3.
  1631. */
  1632. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1633. var rotation = Vector3.Zero();
  1634. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1635. return rotation;
  1636. };
  1637. /**
  1638. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1639. */
  1640. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1641. var quat = MathTmp.Quaternion[0];
  1642. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1643. quat.toEulerAnglesToRef(ref);
  1644. };
  1645. return Vector3;
  1646. }());
  1647. BABYLON.Vector3 = Vector3;
  1648. //Vector4 class created for EulerAngle class conversion to Quaternion
  1649. var Vector4 = (function () {
  1650. /**
  1651. * Creates a Vector4 object from the passed floats.
  1652. */
  1653. function Vector4(x, y, z, w) {
  1654. this.x = x;
  1655. this.y = y;
  1656. this.z = z;
  1657. this.w = w;
  1658. }
  1659. /**
  1660. * Returns the string with the Vector4 coordinates.
  1661. */
  1662. Vector4.prototype.toString = function () {
  1663. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1664. };
  1665. /**
  1666. * Returns the string "Vector4".
  1667. */
  1668. Vector4.prototype.getClassName = function () {
  1669. return "Vector4";
  1670. };
  1671. /**
  1672. * Returns the Vector4 hash code.
  1673. */
  1674. Vector4.prototype.getHashCode = function () {
  1675. var hash = this.x || 0;
  1676. hash = (hash * 397) ^ (this.y || 0);
  1677. hash = (hash * 397) ^ (this.z || 0);
  1678. hash = (hash * 397) ^ (this.w || 0);
  1679. return hash;
  1680. };
  1681. // Operators
  1682. /**
  1683. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1684. */
  1685. Vector4.prototype.asArray = function () {
  1686. var result = [];
  1687. this.toArray(result, 0);
  1688. return result;
  1689. };
  1690. /**
  1691. * Populates the passed array from the passed index with the Vector4 coordinates.
  1692. * Returns the Vector4.
  1693. */
  1694. Vector4.prototype.toArray = function (array, index) {
  1695. if (index === undefined) {
  1696. index = 0;
  1697. }
  1698. array[index] = this.x;
  1699. array[index + 1] = this.y;
  1700. array[index + 2] = this.z;
  1701. array[index + 3] = this.w;
  1702. return this;
  1703. };
  1704. /**
  1705. * Adds the passed vector to the current Vector4.
  1706. * Returns the updated Vector4.
  1707. */
  1708. Vector4.prototype.addInPlace = function (otherVector) {
  1709. this.x += otherVector.x;
  1710. this.y += otherVector.y;
  1711. this.z += otherVector.z;
  1712. this.w += otherVector.w;
  1713. return this;
  1714. };
  1715. /**
  1716. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1717. */
  1718. Vector4.prototype.add = function (otherVector) {
  1719. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1720. };
  1721. /**
  1722. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1723. * Returns the current Vector4.
  1724. */
  1725. Vector4.prototype.addToRef = function (otherVector, result) {
  1726. result.x = this.x + otherVector.x;
  1727. result.y = this.y + otherVector.y;
  1728. result.z = this.z + otherVector.z;
  1729. result.w = this.w + otherVector.w;
  1730. return this;
  1731. };
  1732. /**
  1733. * Subtract in place the passed vector from the current Vector4.
  1734. * Returns the updated Vector4.
  1735. */
  1736. Vector4.prototype.subtractInPlace = function (otherVector) {
  1737. this.x -= otherVector.x;
  1738. this.y -= otherVector.y;
  1739. this.z -= otherVector.z;
  1740. this.w -= otherVector.w;
  1741. return this;
  1742. };
  1743. /**
  1744. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1745. */
  1746. Vector4.prototype.subtract = function (otherVector) {
  1747. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1748. };
  1749. /**
  1750. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1751. * Returns the current Vector4.
  1752. */
  1753. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1754. result.x = this.x - otherVector.x;
  1755. result.y = this.y - otherVector.y;
  1756. result.z = this.z - otherVector.z;
  1757. result.w = this.w - otherVector.w;
  1758. return this;
  1759. };
  1760. /**
  1761. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1762. */
  1763. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1764. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1765. };
  1766. /**
  1767. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1768. * Returns the current Vector4.
  1769. */
  1770. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1771. result.x = this.x - x;
  1772. result.y = this.y - y;
  1773. result.z = this.z - z;
  1774. result.w = this.w - w;
  1775. return this;
  1776. };
  1777. /**
  1778. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1779. */
  1780. Vector4.prototype.negate = function () {
  1781. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1782. };
  1783. /**
  1784. * Multiplies the current Vector4 coordinates by scale (float).
  1785. * Returns the updated Vector4.
  1786. */
  1787. Vector4.prototype.scaleInPlace = function (scale) {
  1788. this.x *= scale;
  1789. this.y *= scale;
  1790. this.z *= scale;
  1791. this.w *= scale;
  1792. return this;
  1793. };
  1794. /**
  1795. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1796. */
  1797. Vector4.prototype.scale = function (scale) {
  1798. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1799. };
  1800. /**
  1801. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1802. * Returns the current Vector4.
  1803. */
  1804. Vector4.prototype.scaleToRef = function (scale, result) {
  1805. result.x = this.x * scale;
  1806. result.y = this.y * scale;
  1807. result.z = this.z * scale;
  1808. result.w = this.w * scale;
  1809. return this;
  1810. };
  1811. /**
  1812. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1813. */
  1814. Vector4.prototype.equals = function (otherVector) {
  1815. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1816. };
  1817. /**
  1818. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1819. */
  1820. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1821. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1822. return otherVector
  1823. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1824. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1825. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1826. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1827. };
  1828. /**
  1829. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1830. */
  1831. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1832. return this.x === x && this.y === y && this.z === z && this.w === w;
  1833. };
  1834. /**
  1835. * Multiplies in place the current Vector4 by the passed one.
  1836. * Returns the updated Vector4.
  1837. */
  1838. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1839. this.x *= otherVector.x;
  1840. this.y *= otherVector.y;
  1841. this.z *= otherVector.z;
  1842. this.w *= otherVector.w;
  1843. return this;
  1844. };
  1845. /**
  1846. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1847. */
  1848. Vector4.prototype.multiply = function (otherVector) {
  1849. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1850. };
  1851. /**
  1852. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1853. * Returns the current Vector4.
  1854. */
  1855. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1856. result.x = this.x * otherVector.x;
  1857. result.y = this.y * otherVector.y;
  1858. result.z = this.z * otherVector.z;
  1859. result.w = this.w * otherVector.w;
  1860. return this;
  1861. };
  1862. /**
  1863. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1864. */
  1865. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1866. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1867. };
  1868. /**
  1869. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1870. */
  1871. Vector4.prototype.divide = function (otherVector) {
  1872. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1873. };
  1874. /**
  1875. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1876. * Returns the current Vector4.
  1877. */
  1878. Vector4.prototype.divideToRef = function (otherVector, result) {
  1879. result.x = this.x / otherVector.x;
  1880. result.y = this.y / otherVector.y;
  1881. result.z = this.z / otherVector.z;
  1882. result.w = this.w / otherVector.w;
  1883. return this;
  1884. };
  1885. /**
  1886. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1887. */
  1888. Vector4.prototype.MinimizeInPlace = function (other) {
  1889. if (other.x < this.x)
  1890. this.x = other.x;
  1891. if (other.y < this.y)
  1892. this.y = other.y;
  1893. if (other.z < this.z)
  1894. this.z = other.z;
  1895. if (other.w < this.w)
  1896. this.w = other.w;
  1897. return this;
  1898. };
  1899. /**
  1900. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1901. */
  1902. Vector4.prototype.MaximizeInPlace = function (other) {
  1903. if (other.x > this.x)
  1904. this.x = other.x;
  1905. if (other.y > this.y)
  1906. this.y = other.y;
  1907. if (other.z > this.z)
  1908. this.z = other.z;
  1909. if (other.w > this.w)
  1910. this.w = other.w;
  1911. return this;
  1912. };
  1913. // Properties
  1914. /**
  1915. * Returns the Vector4 length (float).
  1916. */
  1917. Vector4.prototype.length = function () {
  1918. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1919. };
  1920. /**
  1921. * Returns the Vector4 squared length (float).
  1922. */
  1923. Vector4.prototype.lengthSquared = function () {
  1924. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1925. };
  1926. // Methods
  1927. /**
  1928. * Normalizes in place the Vector4.
  1929. * Returns the updated Vector4.
  1930. */
  1931. Vector4.prototype.normalize = function () {
  1932. var len = this.length();
  1933. if (len === 0)
  1934. return this;
  1935. var num = 1.0 / len;
  1936. this.x *= num;
  1937. this.y *= num;
  1938. this.z *= num;
  1939. this.w *= num;
  1940. return this;
  1941. };
  1942. /**
  1943. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1944. */
  1945. Vector4.prototype.toVector3 = function () {
  1946. return new Vector3(this.x, this.y, this.z);
  1947. };
  1948. /**
  1949. * Returns a new Vector4 copied from the current one.
  1950. */
  1951. Vector4.prototype.clone = function () {
  1952. return new Vector4(this.x, this.y, this.z, this.w);
  1953. };
  1954. /**
  1955. * Updates the current Vector4 with the passed one coordinates.
  1956. * Returns the updated Vector4.
  1957. */
  1958. Vector4.prototype.copyFrom = function (source) {
  1959. this.x = source.x;
  1960. this.y = source.y;
  1961. this.z = source.z;
  1962. this.w = source.w;
  1963. return this;
  1964. };
  1965. /**
  1966. * Updates the current Vector4 coordinates with the passed floats.
  1967. * Returns the updated Vector4.
  1968. */
  1969. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1970. this.x = x;
  1971. this.y = y;
  1972. this.z = z;
  1973. this.w = w;
  1974. return this;
  1975. };
  1976. /**
  1977. * Updates the current Vector4 coordinates with the passed floats.
  1978. * Returns the updated Vector4.
  1979. */
  1980. Vector4.prototype.set = function (x, y, z, w) {
  1981. return this.copyFromFloats(x, y, z, w);
  1982. };
  1983. // Statics
  1984. /**
  1985. * Returns a new Vector4 set from the starting index of the passed array.
  1986. */
  1987. Vector4.FromArray = function (array, offset) {
  1988. if (!offset) {
  1989. offset = 0;
  1990. }
  1991. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1992. };
  1993. /**
  1994. * Updates the passed vector "result" from the starting index of the passed array.
  1995. */
  1996. Vector4.FromArrayToRef = function (array, offset, result) {
  1997. result.x = array[offset];
  1998. result.y = array[offset + 1];
  1999. result.z = array[offset + 2];
  2000. result.w = array[offset + 3];
  2001. };
  2002. /**
  2003. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2004. */
  2005. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2006. result.x = array[offset];
  2007. result.y = array[offset + 1];
  2008. result.z = array[offset + 2];
  2009. result.w = array[offset + 3];
  2010. };
  2011. /**
  2012. * Updates the passed vector "result" coordinates from the passed floats.
  2013. */
  2014. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2015. result.x = x;
  2016. result.y = y;
  2017. result.z = z;
  2018. result.w = w;
  2019. };
  2020. /**
  2021. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2022. */
  2023. Vector4.Zero = function () {
  2024. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2025. };
  2026. /**
  2027. * Returns a new normalized Vector4 from the passed one.
  2028. */
  2029. Vector4.Normalize = function (vector) {
  2030. var result = Vector4.Zero();
  2031. Vector4.NormalizeToRef(vector, result);
  2032. return result;
  2033. };
  2034. /**
  2035. * Updates the passed vector "result" from the normalization of the passed one.
  2036. */
  2037. Vector4.NormalizeToRef = function (vector, result) {
  2038. result.copyFrom(vector);
  2039. result.normalize();
  2040. };
  2041. Vector4.Minimize = function (left, right) {
  2042. var min = left.clone();
  2043. min.MinimizeInPlace(right);
  2044. return min;
  2045. };
  2046. Vector4.Maximize = function (left, right) {
  2047. var max = left.clone();
  2048. max.MaximizeInPlace(right);
  2049. return max;
  2050. };
  2051. /**
  2052. * Returns the distance (float) between the vectors "value1" and "value2".
  2053. */
  2054. Vector4.Distance = function (value1, value2) {
  2055. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2056. };
  2057. /**
  2058. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2059. */
  2060. Vector4.DistanceSquared = function (value1, value2) {
  2061. var x = value1.x - value2.x;
  2062. var y = value1.y - value2.y;
  2063. var z = value1.z - value2.z;
  2064. var w = value1.w - value2.w;
  2065. return (x * x) + (y * y) + (z * z) + (w * w);
  2066. };
  2067. /**
  2068. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2069. */
  2070. Vector4.Center = function (value1, value2) {
  2071. var center = value1.add(value2);
  2072. center.scaleInPlace(0.5);
  2073. return center;
  2074. };
  2075. /**
  2076. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2077. * This methods computes transformed normalized direction vectors only.
  2078. */
  2079. Vector4.TransformNormal = function (vector, transformation) {
  2080. var result = Vector4.Zero();
  2081. Vector4.TransformNormalToRef(vector, transformation, result);
  2082. return result;
  2083. };
  2084. /**
  2085. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2086. * This methods computes transformed normalized direction vectors only.
  2087. */
  2088. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2089. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2090. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2091. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2092. result.x = x;
  2093. result.y = y;
  2094. result.z = z;
  2095. result.w = vector.w;
  2096. };
  2097. /**
  2098. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2099. * This methods computes transformed normalized direction vectors only.
  2100. */
  2101. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2102. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2103. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2104. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2105. result.w = w;
  2106. };
  2107. return Vector4;
  2108. }());
  2109. BABYLON.Vector4 = Vector4;
  2110. var Size = (function () {
  2111. /**
  2112. * Creates a Size object from the passed width and height (floats).
  2113. */
  2114. function Size(width, height) {
  2115. this.width = width;
  2116. this.height = height;
  2117. }
  2118. // Returns a string with the Size width and height.
  2119. Size.prototype.toString = function () {
  2120. return "{W: " + this.width + ", H: " + this.height + "}";
  2121. };
  2122. /**
  2123. * Returns the string "Size"
  2124. */
  2125. Size.prototype.getClassName = function () {
  2126. return "Size";
  2127. };
  2128. /**
  2129. * Returns the Size hash code.
  2130. */
  2131. Size.prototype.getHashCode = function () {
  2132. var hash = this.width || 0;
  2133. hash = (hash * 397) ^ (this.height || 0);
  2134. return hash;
  2135. };
  2136. /**
  2137. * Updates the current size from the passed one.
  2138. * Returns the updated Size.
  2139. */
  2140. Size.prototype.copyFrom = function (src) {
  2141. this.width = src.width;
  2142. this.height = src.height;
  2143. };
  2144. /**
  2145. * Updates in place the current Size from the passed floats.
  2146. * Returns the updated Size.
  2147. */
  2148. Size.prototype.copyFromFloats = function (width, height) {
  2149. this.width = width;
  2150. this.height = height;
  2151. return this;
  2152. };
  2153. /**
  2154. * Updates in place the current Size from the passed floats.
  2155. * Returns the updated Size.
  2156. */
  2157. Size.prototype.set = function (width, height) {
  2158. return this.copyFromFloats(width, height);
  2159. };
  2160. /**
  2161. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2162. */
  2163. Size.prototype.multiplyByFloats = function (w, h) {
  2164. return new Size(this.width * w, this.height * h);
  2165. };
  2166. /**
  2167. * Returns a new Size copied from the passed one.
  2168. */
  2169. Size.prototype.clone = function () {
  2170. return new Size(this.width, this.height);
  2171. };
  2172. /**
  2173. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2174. */
  2175. Size.prototype.equals = function (other) {
  2176. if (!other) {
  2177. return false;
  2178. }
  2179. return (this.width === other.width) && (this.height === other.height);
  2180. };
  2181. Object.defineProperty(Size.prototype, "surface", {
  2182. /**
  2183. * Returns the surface of the Size : width * height (float).
  2184. */
  2185. get: function () {
  2186. return this.width * this.height;
  2187. },
  2188. enumerable: true,
  2189. configurable: true
  2190. });
  2191. /**
  2192. * Returns a new Size set to (0.0, 0.0)
  2193. */
  2194. Size.Zero = function () {
  2195. return new Size(0.0, 0.0);
  2196. };
  2197. /**
  2198. * Returns a new Size set as the addition result of the current Size and the passed one.
  2199. */
  2200. Size.prototype.add = function (otherSize) {
  2201. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2202. return r;
  2203. };
  2204. /**
  2205. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2206. */
  2207. Size.prototype.subtract = function (otherSize) {
  2208. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2209. return r;
  2210. };
  2211. /**
  2212. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2213. */
  2214. Size.Lerp = function (start, end, amount) {
  2215. var w = start.width + ((end.width - start.width) * amount);
  2216. var h = start.height + ((end.height - start.height) * amount);
  2217. return new Size(w, h);
  2218. };
  2219. return Size;
  2220. }());
  2221. BABYLON.Size = Size;
  2222. var Quaternion = (function () {
  2223. /**
  2224. * Creates a new Quaternion from the passed floats.
  2225. */
  2226. function Quaternion(x, y, z, w) {
  2227. if (x === void 0) { x = 0.0; }
  2228. if (y === void 0) { y = 0.0; }
  2229. if (z === void 0) { z = 0.0; }
  2230. if (w === void 0) { w = 1.0; }
  2231. this.x = x;
  2232. this.y = y;
  2233. this.z = z;
  2234. this.w = w;
  2235. }
  2236. /**
  2237. * Returns a string with the Quaternion coordinates.
  2238. */
  2239. Quaternion.prototype.toString = function () {
  2240. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2241. };
  2242. /**
  2243. * Returns the string "Quaternion".
  2244. */
  2245. Quaternion.prototype.getClassName = function () {
  2246. return "Quaternion";
  2247. };
  2248. /**
  2249. * Returns the Quaternion hash code.
  2250. */
  2251. Quaternion.prototype.getHashCode = function () {
  2252. var hash = this.x || 0;
  2253. hash = (hash * 397) ^ (this.y || 0);
  2254. hash = (hash * 397) ^ (this.z || 0);
  2255. hash = (hash * 397) ^ (this.w || 0);
  2256. return hash;
  2257. };
  2258. /**
  2259. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2260. */
  2261. Quaternion.prototype.asArray = function () {
  2262. return [this.x, this.y, this.z, this.w];
  2263. };
  2264. /**
  2265. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2266. */
  2267. Quaternion.prototype.equals = function (otherQuaternion) {
  2268. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2269. };
  2270. /**
  2271. * Returns a new Quaternion copied from the current one.
  2272. */
  2273. Quaternion.prototype.clone = function () {
  2274. return new Quaternion(this.x, this.y, this.z, this.w);
  2275. };
  2276. /**
  2277. * Updates the current Quaternion from the passed one coordinates.
  2278. * Returns the updated Quaterion.
  2279. */
  2280. Quaternion.prototype.copyFrom = function (other) {
  2281. this.x = other.x;
  2282. this.y = other.y;
  2283. this.z = other.z;
  2284. this.w = other.w;
  2285. return this;
  2286. };
  2287. /**
  2288. * Updates the current Quaternion from the passed float coordinates.
  2289. * Returns the updated Quaterion.
  2290. */
  2291. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2292. this.x = x;
  2293. this.y = y;
  2294. this.z = z;
  2295. this.w = w;
  2296. return this;
  2297. };
  2298. /**
  2299. * Updates the current Quaternion from the passed float coordinates.
  2300. * Returns the updated Quaterion.
  2301. */
  2302. Quaternion.prototype.set = function (x, y, z, w) {
  2303. return this.copyFromFloats(x, y, z, w);
  2304. };
  2305. /**
  2306. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2307. */
  2308. Quaternion.prototype.add = function (other) {
  2309. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2310. };
  2311. /**
  2312. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2313. */
  2314. Quaternion.prototype.subtract = function (other) {
  2315. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2316. };
  2317. /**
  2318. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2319. */
  2320. Quaternion.prototype.scale = function (value) {
  2321. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2322. };
  2323. /**
  2324. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2325. */
  2326. Quaternion.prototype.multiply = function (q1) {
  2327. var result = new Quaternion(0, 0, 0, 1.0);
  2328. this.multiplyToRef(q1, result);
  2329. return result;
  2330. };
  2331. /**
  2332. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2333. * Returns the current Quaternion.
  2334. */
  2335. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2336. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2337. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2338. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2339. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2340. result.copyFromFloats(x, y, z, w);
  2341. return this;
  2342. };
  2343. /**
  2344. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2345. * Returns the updated Quaternion.
  2346. */
  2347. Quaternion.prototype.multiplyInPlace = function (q1) {
  2348. this.multiplyToRef(q1, this);
  2349. return this;
  2350. };
  2351. /**
  2352. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2353. * Returns the current Quaternion.
  2354. */
  2355. Quaternion.prototype.conjugateToRef = function (ref) {
  2356. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2357. return this;
  2358. };
  2359. /**
  2360. * Conjugates in place the current Quaternion.
  2361. * Returns the updated Quaternion.
  2362. */
  2363. Quaternion.prototype.conjugateInPlace = function () {
  2364. this.x *= -1;
  2365. this.y *= -1;
  2366. this.z *= -1;
  2367. return this;
  2368. };
  2369. /**
  2370. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2371. */
  2372. Quaternion.prototype.conjugate = function () {
  2373. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2374. return result;
  2375. };
  2376. /**
  2377. * Returns the Quaternion length (float).
  2378. */
  2379. Quaternion.prototype.length = function () {
  2380. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2381. };
  2382. /**
  2383. * Normalize in place the current Quaternion.
  2384. * Returns the updated Quaternion.
  2385. */
  2386. Quaternion.prototype.normalize = function () {
  2387. var length = 1.0 / this.length();
  2388. this.x *= length;
  2389. this.y *= length;
  2390. this.z *= length;
  2391. this.w *= length;
  2392. return this;
  2393. };
  2394. /**
  2395. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2396. */
  2397. Quaternion.prototype.toEulerAngles = function (order) {
  2398. if (order === void 0) { order = "YZX"; }
  2399. var result = Vector3.Zero();
  2400. this.toEulerAnglesToRef(result, order);
  2401. return result;
  2402. };
  2403. /**
  2404. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2405. * Returns the current Quaternion.
  2406. */
  2407. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2408. if (order === void 0) { order = "YZX"; }
  2409. var qz = this.z;
  2410. var qx = this.x;
  2411. var qy = this.y;
  2412. var qw = this.w;
  2413. var sqw = qw * qw;
  2414. var sqz = qz * qz;
  2415. var sqx = qx * qx;
  2416. var sqy = qy * qy;
  2417. var zAxisY = qy * qz - qx * qw;
  2418. var limit = .4999999;
  2419. if (zAxisY < -limit) {
  2420. result.y = 2 * Math.atan2(qy, qw);
  2421. result.x = Math.PI / 2;
  2422. result.z = 0;
  2423. }
  2424. else if (zAxisY > limit) {
  2425. result.y = 2 * Math.atan2(qy, qw);
  2426. result.x = -Math.PI / 2;
  2427. result.z = 0;
  2428. }
  2429. else {
  2430. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2431. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2432. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2433. }
  2434. return this;
  2435. };
  2436. /**
  2437. * Updates the passed rotation matrix with the current Quaternion values.
  2438. * Returns the current Quaternion.
  2439. */
  2440. Quaternion.prototype.toRotationMatrix = function (result) {
  2441. var xx = this.x * this.x;
  2442. var yy = this.y * this.y;
  2443. var zz = this.z * this.z;
  2444. var xy = this.x * this.y;
  2445. var zw = this.z * this.w;
  2446. var zx = this.z * this.x;
  2447. var yw = this.y * this.w;
  2448. var yz = this.y * this.z;
  2449. var xw = this.x * this.w;
  2450. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2451. result.m[1] = 2.0 * (xy + zw);
  2452. result.m[2] = 2.0 * (zx - yw);
  2453. result.m[3] = 0;
  2454. result.m[4] = 2.0 * (xy - zw);
  2455. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2456. result.m[6] = 2.0 * (yz + xw);
  2457. result.m[7] = 0;
  2458. result.m[8] = 2.0 * (zx + yw);
  2459. result.m[9] = 2.0 * (yz - xw);
  2460. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2461. result.m[11] = 0;
  2462. result.m[12] = 0;
  2463. result.m[13] = 0;
  2464. result.m[14] = 0;
  2465. result.m[15] = 1.0;
  2466. return this;
  2467. };
  2468. /**
  2469. * Updates the current Quaternion from the passed rotation matrix values.
  2470. * Returns the updated Quaternion.
  2471. */
  2472. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2473. Quaternion.FromRotationMatrixToRef(matrix, this);
  2474. return this;
  2475. };
  2476. // Statics
  2477. /**
  2478. * Returns a new Quaternion set from the passed rotation matrix values.
  2479. */
  2480. Quaternion.FromRotationMatrix = function (matrix) {
  2481. var result = new Quaternion();
  2482. Quaternion.FromRotationMatrixToRef(matrix, result);
  2483. return result;
  2484. };
  2485. /**
  2486. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2487. */
  2488. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2489. var data = matrix.m;
  2490. var m11 = data[0], m12 = data[4], m13 = data[8];
  2491. var m21 = data[1], m22 = data[5], m23 = data[9];
  2492. var m31 = data[2], m32 = data[6], m33 = data[10];
  2493. var trace = m11 + m22 + m33;
  2494. var s;
  2495. if (trace > 0) {
  2496. s = 0.5 / Math.sqrt(trace + 1.0);
  2497. result.w = 0.25 / s;
  2498. result.x = (m32 - m23) * s;
  2499. result.y = (m13 - m31) * s;
  2500. result.z = (m21 - m12) * s;
  2501. }
  2502. else if (m11 > m22 && m11 > m33) {
  2503. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2504. result.w = (m32 - m23) / s;
  2505. result.x = 0.25 * s;
  2506. result.y = (m12 + m21) / s;
  2507. result.z = (m13 + m31) / s;
  2508. }
  2509. else if (m22 > m33) {
  2510. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2511. result.w = (m13 - m31) / s;
  2512. result.x = (m12 + m21) / s;
  2513. result.y = 0.25 * s;
  2514. result.z = (m23 + m32) / s;
  2515. }
  2516. else {
  2517. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2518. result.w = (m21 - m12) / s;
  2519. result.x = (m13 + m31) / s;
  2520. result.y = (m23 + m32) / s;
  2521. result.z = 0.25 * s;
  2522. }
  2523. };
  2524. /**
  2525. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2526. */
  2527. Quaternion.Zero = function () {
  2528. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2529. };
  2530. /**
  2531. * Returns a new Quaternion as the inverted current Quaternion.
  2532. */
  2533. Quaternion.Inverse = function (q) {
  2534. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2535. };
  2536. /**
  2537. * Returns the identity Quaternion.
  2538. */
  2539. Quaternion.Identity = function () {
  2540. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2541. };
  2542. Quaternion.IsIdentity = function (quaternion) {
  2543. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2544. };
  2545. /**
  2546. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2547. */
  2548. Quaternion.RotationAxis = function (axis, angle) {
  2549. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2550. };
  2551. /**
  2552. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2553. */
  2554. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2555. var sin = Math.sin(angle / 2);
  2556. axis.normalize();
  2557. result.w = Math.cos(angle / 2);
  2558. result.x = axis.x * sin;
  2559. result.y = axis.y * sin;
  2560. result.z = axis.z * sin;
  2561. return result;
  2562. };
  2563. /**
  2564. * Retuns a new Quaternion set from the starting index of the passed array.
  2565. */
  2566. Quaternion.FromArray = function (array, offset) {
  2567. if (!offset) {
  2568. offset = 0;
  2569. }
  2570. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2571. };
  2572. /**
  2573. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2574. */
  2575. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2576. var q = new Quaternion();
  2577. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2578. return q;
  2579. };
  2580. /**
  2581. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2582. */
  2583. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2584. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2585. var halfRoll = roll * 0.5;
  2586. var halfPitch = pitch * 0.5;
  2587. var halfYaw = yaw * 0.5;
  2588. var sinRoll = Math.sin(halfRoll);
  2589. var cosRoll = Math.cos(halfRoll);
  2590. var sinPitch = Math.sin(halfPitch);
  2591. var cosPitch = Math.cos(halfPitch);
  2592. var sinYaw = Math.sin(halfYaw);
  2593. var cosYaw = Math.cos(halfYaw);
  2594. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2595. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2596. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2597. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2598. };
  2599. /**
  2600. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2601. */
  2602. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2603. var result = new Quaternion();
  2604. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2605. return result;
  2606. };
  2607. /**
  2608. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2609. */
  2610. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2611. // Produces a quaternion from Euler angles in the z-x-z orientation
  2612. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2613. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2614. var halfBeta = beta * 0.5;
  2615. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2616. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2617. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2618. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2619. };
  2620. /**
  2621. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2622. * cf to Vector3.RotationFromAxis() documentation.
  2623. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2624. */
  2625. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2626. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2627. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2628. return quat;
  2629. };
  2630. /**
  2631. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2632. * cf to Vector3.RotationFromAxis() documentation.
  2633. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2634. */
  2635. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2636. var rotMat = MathTmp.Matrix[0];
  2637. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2638. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2639. };
  2640. Quaternion.Slerp = function (left, right, amount) {
  2641. var result = Quaternion.Identity();
  2642. Quaternion.SlerpToRef(left, right, amount, result);
  2643. return result;
  2644. };
  2645. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2646. var num2;
  2647. var num3;
  2648. var num = amount;
  2649. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2650. var flag = false;
  2651. if (num4 < 0) {
  2652. flag = true;
  2653. num4 = -num4;
  2654. }
  2655. if (num4 > 0.999999) {
  2656. num3 = 1 - num;
  2657. num2 = flag ? -num : num;
  2658. }
  2659. else {
  2660. var num5 = Math.acos(num4);
  2661. var num6 = (1.0 / Math.sin(num5));
  2662. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2663. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2664. }
  2665. result.x = (num3 * left.x) + (num2 * right.x);
  2666. result.y = (num3 * left.y) + (num2 * right.y);
  2667. result.z = (num3 * left.z) + (num2 * right.z);
  2668. result.w = (num3 * left.w) + (num2 * right.w);
  2669. };
  2670. return Quaternion;
  2671. }());
  2672. BABYLON.Quaternion = Quaternion;
  2673. var Matrix = (function () {
  2674. function Matrix() {
  2675. this.m = new Float32Array(16);
  2676. }
  2677. // Properties
  2678. /**
  2679. * Boolean : True is the matrix is the identity matrix
  2680. */
  2681. Matrix.prototype.isIdentity = function () {
  2682. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2683. return false;
  2684. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2685. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2686. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2687. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2688. return false;
  2689. return true;
  2690. };
  2691. /**
  2692. * Returns the matrix determinant (float).
  2693. */
  2694. Matrix.prototype.determinant = function () {
  2695. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2696. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2697. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2698. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2699. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2700. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2701. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2702. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2703. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2704. };
  2705. // Methods
  2706. /**
  2707. * Returns the matrix underlying array.
  2708. */
  2709. Matrix.prototype.toArray = function () {
  2710. return this.m;
  2711. };
  2712. /**
  2713. * Returns the matrix underlying array.
  2714. */
  2715. Matrix.prototype.asArray = function () {
  2716. return this.toArray();
  2717. };
  2718. /**
  2719. * Inverts in place the Matrix.
  2720. * Returns the Matrix inverted.
  2721. */
  2722. Matrix.prototype.invert = function () {
  2723. this.invertToRef(this);
  2724. return this;
  2725. };
  2726. /**
  2727. * Sets all the matrix elements to zero.
  2728. * Returns the Matrix.
  2729. */
  2730. Matrix.prototype.reset = function () {
  2731. for (var index = 0; index < 16; index++) {
  2732. this.m[index] = 0.0;
  2733. }
  2734. return this;
  2735. };
  2736. /**
  2737. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2738. */
  2739. Matrix.prototype.add = function (other) {
  2740. var result = new Matrix();
  2741. this.addToRef(other, result);
  2742. return result;
  2743. };
  2744. /**
  2745. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2746. * Returns the Matrix.
  2747. */
  2748. Matrix.prototype.addToRef = function (other, result) {
  2749. for (var index = 0; index < 16; index++) {
  2750. result.m[index] = this.m[index] + other.m[index];
  2751. }
  2752. return this;
  2753. };
  2754. /**
  2755. * Adds in place the passed matrix to the current Matrix.
  2756. * Returns the updated Matrix.
  2757. */
  2758. Matrix.prototype.addToSelf = function (other) {
  2759. for (var index = 0; index < 16; index++) {
  2760. this.m[index] += other.m[index];
  2761. }
  2762. return this;
  2763. };
  2764. /**
  2765. * Sets the passed matrix with the current inverted Matrix.
  2766. * Returns the unmodified current Matrix.
  2767. */
  2768. Matrix.prototype.invertToRef = function (other) {
  2769. var l1 = this.m[0];
  2770. var l2 = this.m[1];
  2771. var l3 = this.m[2];
  2772. var l4 = this.m[3];
  2773. var l5 = this.m[4];
  2774. var l6 = this.m[5];
  2775. var l7 = this.m[6];
  2776. var l8 = this.m[7];
  2777. var l9 = this.m[8];
  2778. var l10 = this.m[9];
  2779. var l11 = this.m[10];
  2780. var l12 = this.m[11];
  2781. var l13 = this.m[12];
  2782. var l14 = this.m[13];
  2783. var l15 = this.m[14];
  2784. var l16 = this.m[15];
  2785. var l17 = (l11 * l16) - (l12 * l15);
  2786. var l18 = (l10 * l16) - (l12 * l14);
  2787. var l19 = (l10 * l15) - (l11 * l14);
  2788. var l20 = (l9 * l16) - (l12 * l13);
  2789. var l21 = (l9 * l15) - (l11 * l13);
  2790. var l22 = (l9 * l14) - (l10 * l13);
  2791. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2792. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2793. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2794. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2795. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2796. var l28 = (l7 * l16) - (l8 * l15);
  2797. var l29 = (l6 * l16) - (l8 * l14);
  2798. var l30 = (l6 * l15) - (l7 * l14);
  2799. var l31 = (l5 * l16) - (l8 * l13);
  2800. var l32 = (l5 * l15) - (l7 * l13);
  2801. var l33 = (l5 * l14) - (l6 * l13);
  2802. var l34 = (l7 * l12) - (l8 * l11);
  2803. var l35 = (l6 * l12) - (l8 * l10);
  2804. var l36 = (l6 * l11) - (l7 * l10);
  2805. var l37 = (l5 * l12) - (l8 * l9);
  2806. var l38 = (l5 * l11) - (l7 * l9);
  2807. var l39 = (l5 * l10) - (l6 * l9);
  2808. other.m[0] = l23 * l27;
  2809. other.m[4] = l24 * l27;
  2810. other.m[8] = l25 * l27;
  2811. other.m[12] = l26 * l27;
  2812. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2813. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2814. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2815. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2816. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2817. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2818. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2819. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2820. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2821. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2822. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2823. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2824. return this;
  2825. };
  2826. /**
  2827. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2828. * Returns the updated Matrix.
  2829. */
  2830. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2831. this.m[12] = x;
  2832. this.m[13] = y;
  2833. this.m[14] = z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Inserts the translation vector in the current Matrix.
  2838. * Returns the updated Matrix.
  2839. */
  2840. Matrix.prototype.setTranslation = function (vector3) {
  2841. this.m[12] = vector3.x;
  2842. this.m[13] = vector3.y;
  2843. this.m[14] = vector3.z;
  2844. return this;
  2845. };
  2846. /**
  2847. * Returns a new Vector3 as the extracted translation from the Matrix.
  2848. */
  2849. Matrix.prototype.getTranslation = function () {
  2850. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2851. };
  2852. /**
  2853. * Fill a Vector3 with the extracted translation from the Matrix.
  2854. */
  2855. Matrix.prototype.getTranslationToRef = function (result) {
  2856. result.x = this.m[12];
  2857. result.y = this.m[13];
  2858. result.z = this.m[14];
  2859. return this;
  2860. };
  2861. /**
  2862. * Remove rotation and scaling part from the Matrix.
  2863. * Returns the updated Matrix.
  2864. */
  2865. Matrix.prototype.removeRotationAndScaling = function () {
  2866. this.setRowFromFloats(0, 1, 0, 0, 0);
  2867. this.setRowFromFloats(1, 0, 1, 0, 0);
  2868. this.setRowFromFloats(2, 0, 0, 1, 0);
  2869. return this;
  2870. };
  2871. /**
  2872. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2873. */
  2874. Matrix.prototype.multiply = function (other) {
  2875. var result = new Matrix();
  2876. this.multiplyToRef(other, result);
  2877. return result;
  2878. };
  2879. /**
  2880. * Updates the current Matrix from the passed one values.
  2881. * Returns the updated Matrix.
  2882. */
  2883. Matrix.prototype.copyFrom = function (other) {
  2884. for (var index = 0; index < 16; index++) {
  2885. this.m[index] = other.m[index];
  2886. }
  2887. return this;
  2888. };
  2889. /**
  2890. * Populates the passed array from the starting index with the Matrix values.
  2891. * Returns the Matrix.
  2892. */
  2893. Matrix.prototype.copyToArray = function (array, offset) {
  2894. if (offset === void 0) { offset = 0; }
  2895. for (var index = 0; index < 16; index++) {
  2896. array[offset + index] = this.m[index];
  2897. }
  2898. return this;
  2899. };
  2900. /**
  2901. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2902. */
  2903. Matrix.prototype.multiplyToRef = function (other, result) {
  2904. this.multiplyToArray(other, result.m, 0);
  2905. return this;
  2906. };
  2907. /**
  2908. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2909. */
  2910. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2911. var tm0 = this.m[0];
  2912. var tm1 = this.m[1];
  2913. var tm2 = this.m[2];
  2914. var tm3 = this.m[3];
  2915. var tm4 = this.m[4];
  2916. var tm5 = this.m[5];
  2917. var tm6 = this.m[6];
  2918. var tm7 = this.m[7];
  2919. var tm8 = this.m[8];
  2920. var tm9 = this.m[9];
  2921. var tm10 = this.m[10];
  2922. var tm11 = this.m[11];
  2923. var tm12 = this.m[12];
  2924. var tm13 = this.m[13];
  2925. var tm14 = this.m[14];
  2926. var tm15 = this.m[15];
  2927. var om0 = other.m[0];
  2928. var om1 = other.m[1];
  2929. var om2 = other.m[2];
  2930. var om3 = other.m[3];
  2931. var om4 = other.m[4];
  2932. var om5 = other.m[5];
  2933. var om6 = other.m[6];
  2934. var om7 = other.m[7];
  2935. var om8 = other.m[8];
  2936. var om9 = other.m[9];
  2937. var om10 = other.m[10];
  2938. var om11 = other.m[11];
  2939. var om12 = other.m[12];
  2940. var om13 = other.m[13];
  2941. var om14 = other.m[14];
  2942. var om15 = other.m[15];
  2943. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2944. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2945. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2946. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2947. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2948. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2949. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2950. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2951. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2952. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2953. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  2954. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  2955. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  2956. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  2957. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  2958. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  2959. return this;
  2960. };
  2961. /**
  2962. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  2963. */
  2964. Matrix.prototype.equals = function (value) {
  2965. return value &&
  2966. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  2967. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  2968. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  2969. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  2970. };
  2971. /**
  2972. * Returns a new Matrix from the current Matrix.
  2973. */
  2974. Matrix.prototype.clone = function () {
  2975. 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]);
  2976. };
  2977. /**
  2978. * Returns the string "Matrix"
  2979. */
  2980. Matrix.prototype.getClassName = function () {
  2981. return "Matrix";
  2982. };
  2983. /**
  2984. * Returns the Matrix hash code.
  2985. */
  2986. Matrix.prototype.getHashCode = function () {
  2987. var hash = this.m[0] || 0;
  2988. for (var i = 1; i < 16; i++) {
  2989. hash = (hash * 397) ^ (this.m[i] || 0);
  2990. }
  2991. return hash;
  2992. };
  2993. /**
  2994. * Decomposes the current Matrix into :
  2995. * - a scale vector3 passed as a reference to update,
  2996. * - a rotation quaternion passed as a reference to update,
  2997. * - a translation vector3 passed as a reference to update.
  2998. * Returns the boolean `true`.
  2999. */
  3000. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3001. translation.x = this.m[12];
  3002. translation.y = this.m[13];
  3003. translation.z = this.m[14];
  3004. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3005. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3006. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3007. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3008. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3009. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3010. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3011. rotation.x = 0;
  3012. rotation.y = 0;
  3013. rotation.z = 0;
  3014. rotation.w = 1;
  3015. return false;
  3016. }
  3017. 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]);
  3018. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3019. return true;
  3020. };
  3021. /**
  3022. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3023. */
  3024. Matrix.prototype.getRotationMatrix = function () {
  3025. var result = Matrix.Identity();
  3026. this.getRotationMatrixToRef(result);
  3027. return result;
  3028. };
  3029. /**
  3030. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3031. * Returns the current Matrix.
  3032. */
  3033. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3034. var m = this.m;
  3035. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3036. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3037. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3038. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3039. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3040. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3041. 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);
  3042. return this;
  3043. };
  3044. // Statics
  3045. /**
  3046. * Returns a new Matrix set from the starting index of the passed array.
  3047. */
  3048. Matrix.FromArray = function (array, offset) {
  3049. var result = new Matrix();
  3050. if (!offset) {
  3051. offset = 0;
  3052. }
  3053. Matrix.FromArrayToRef(array, offset, result);
  3054. return result;
  3055. };
  3056. /**
  3057. * Sets the passed "result" matrix from the starting index of the passed array.
  3058. */
  3059. Matrix.FromArrayToRef = function (array, offset, result) {
  3060. for (var index = 0; index < 16; index++) {
  3061. result.m[index] = array[index + offset];
  3062. }
  3063. };
  3064. /**
  3065. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3066. */
  3067. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3068. for (var index = 0; index < 16; index++) {
  3069. result.m[index] = array[index + offset] * scale;
  3070. }
  3071. };
  3072. /**
  3073. * Sets the passed matrix "result" with the 16 passed floats.
  3074. */
  3075. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3076. result.m[0] = initialM11;
  3077. result.m[1] = initialM12;
  3078. result.m[2] = initialM13;
  3079. result.m[3] = initialM14;
  3080. result.m[4] = initialM21;
  3081. result.m[5] = initialM22;
  3082. result.m[6] = initialM23;
  3083. result.m[7] = initialM24;
  3084. result.m[8] = initialM31;
  3085. result.m[9] = initialM32;
  3086. result.m[10] = initialM33;
  3087. result.m[11] = initialM34;
  3088. result.m[12] = initialM41;
  3089. result.m[13] = initialM42;
  3090. result.m[14] = initialM43;
  3091. result.m[15] = initialM44;
  3092. };
  3093. /**
  3094. * Returns the index-th row of the current matrix as a new Vector4.
  3095. */
  3096. Matrix.prototype.getRow = function (index) {
  3097. if (index < 0 || index > 3) {
  3098. return null;
  3099. }
  3100. var i = index * 4;
  3101. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3102. };
  3103. /**
  3104. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3105. * Returns the updated Matrix.
  3106. */
  3107. Matrix.prototype.setRow = function (index, row) {
  3108. if (index < 0 || index > 3) {
  3109. return this;
  3110. }
  3111. var i = index * 4;
  3112. this.m[i + 0] = row.x;
  3113. this.m[i + 1] = row.y;
  3114. this.m[i + 2] = row.z;
  3115. this.m[i + 3] = row.w;
  3116. return this;
  3117. };
  3118. /**
  3119. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3120. * Returns the updated Matrix.
  3121. */
  3122. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3123. if (index < 0 || index > 3) {
  3124. return this;
  3125. }
  3126. var i = index * 4;
  3127. this.m[i + 0] = x;
  3128. this.m[i + 1] = y;
  3129. this.m[i + 2] = z;
  3130. this.m[i + 3] = w;
  3131. return this;
  3132. };
  3133. /**
  3134. * Returns a new Matrix set from the 16 passed floats.
  3135. */
  3136. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3137. var result = new Matrix();
  3138. result.m[0] = initialM11;
  3139. result.m[1] = initialM12;
  3140. result.m[2] = initialM13;
  3141. result.m[3] = initialM14;
  3142. result.m[4] = initialM21;
  3143. result.m[5] = initialM22;
  3144. result.m[6] = initialM23;
  3145. result.m[7] = initialM24;
  3146. result.m[8] = initialM31;
  3147. result.m[9] = initialM32;
  3148. result.m[10] = initialM33;
  3149. result.m[11] = initialM34;
  3150. result.m[12] = initialM41;
  3151. result.m[13] = initialM42;
  3152. result.m[14] = initialM43;
  3153. result.m[15] = initialM44;
  3154. return result;
  3155. };
  3156. /**
  3157. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3158. */
  3159. Matrix.Compose = function (scale, rotation, translation) {
  3160. var result = Matrix.Identity();
  3161. Matrix.ComposeToRef(scale, rotation, translation, result);
  3162. return result;
  3163. };
  3164. /**
  3165. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3166. */
  3167. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3168. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3169. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3170. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3171. result.setTranslation(translation);
  3172. };
  3173. /**
  3174. * Returns a new indentity Matrix.
  3175. */
  3176. Matrix.Identity = function () {
  3177. 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);
  3178. };
  3179. /**
  3180. * Sets the passed "result" as an identity matrix.
  3181. */
  3182. Matrix.IdentityToRef = function (result) {
  3183. 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);
  3184. };
  3185. /**
  3186. * Returns a new zero Matrix.
  3187. */
  3188. Matrix.Zero = function () {
  3189. 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);
  3190. };
  3191. /**
  3192. * Returns a new rotation matrix for "angle" radians around the X axis.
  3193. */
  3194. Matrix.RotationX = function (angle) {
  3195. var result = new Matrix();
  3196. Matrix.RotationXToRef(angle, result);
  3197. return result;
  3198. };
  3199. /**
  3200. * Returns a new Matrix as the passed inverted one.
  3201. */
  3202. Matrix.Invert = function (source) {
  3203. var result = new Matrix();
  3204. source.invertToRef(result);
  3205. return result;
  3206. };
  3207. /**
  3208. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3209. */
  3210. Matrix.RotationXToRef = function (angle, result) {
  3211. var s = Math.sin(angle);
  3212. var c = Math.cos(angle);
  3213. result.m[0] = 1.0;
  3214. result.m[15] = 1.0;
  3215. result.m[5] = c;
  3216. result.m[10] = c;
  3217. result.m[9] = -s;
  3218. result.m[6] = s;
  3219. result.m[1] = 0.0;
  3220. result.m[2] = 0.0;
  3221. result.m[3] = 0.0;
  3222. result.m[4] = 0.0;
  3223. result.m[7] = 0.0;
  3224. result.m[8] = 0.0;
  3225. result.m[11] = 0.0;
  3226. result.m[12] = 0.0;
  3227. result.m[13] = 0.0;
  3228. result.m[14] = 0.0;
  3229. };
  3230. /**
  3231. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3232. */
  3233. Matrix.RotationY = function (angle) {
  3234. var result = new Matrix();
  3235. Matrix.RotationYToRef(angle, result);
  3236. return result;
  3237. };
  3238. /**
  3239. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3240. */
  3241. Matrix.RotationYToRef = function (angle, result) {
  3242. var s = Math.sin(angle);
  3243. var c = Math.cos(angle);
  3244. result.m[5] = 1.0;
  3245. result.m[15] = 1.0;
  3246. result.m[0] = c;
  3247. result.m[2] = -s;
  3248. result.m[8] = s;
  3249. result.m[10] = c;
  3250. result.m[1] = 0.0;
  3251. result.m[3] = 0.0;
  3252. result.m[4] = 0.0;
  3253. result.m[6] = 0.0;
  3254. result.m[7] = 0.0;
  3255. result.m[9] = 0.0;
  3256. result.m[11] = 0.0;
  3257. result.m[12] = 0.0;
  3258. result.m[13] = 0.0;
  3259. result.m[14] = 0.0;
  3260. };
  3261. /**
  3262. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3263. */
  3264. Matrix.RotationZ = function (angle) {
  3265. var result = new Matrix();
  3266. Matrix.RotationZToRef(angle, result);
  3267. return result;
  3268. };
  3269. /**
  3270. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3271. */
  3272. Matrix.RotationZToRef = function (angle, result) {
  3273. var s = Math.sin(angle);
  3274. var c = Math.cos(angle);
  3275. result.m[10] = 1.0;
  3276. result.m[15] = 1.0;
  3277. result.m[0] = c;
  3278. result.m[1] = s;
  3279. result.m[4] = -s;
  3280. result.m[5] = c;
  3281. result.m[2] = 0.0;
  3282. result.m[3] = 0.0;
  3283. result.m[6] = 0.0;
  3284. result.m[7] = 0.0;
  3285. result.m[8] = 0.0;
  3286. result.m[9] = 0.0;
  3287. result.m[11] = 0.0;
  3288. result.m[12] = 0.0;
  3289. result.m[13] = 0.0;
  3290. result.m[14] = 0.0;
  3291. };
  3292. /**
  3293. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3294. */
  3295. Matrix.RotationAxis = function (axis, angle) {
  3296. var result = Matrix.Zero();
  3297. Matrix.RotationAxisToRef(axis, angle, result);
  3298. return result;
  3299. };
  3300. /**
  3301. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3302. */
  3303. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3304. var s = Math.sin(-angle);
  3305. var c = Math.cos(-angle);
  3306. var c1 = 1 - c;
  3307. axis.normalize();
  3308. result.m[0] = (axis.x * axis.x) * c1 + c;
  3309. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3310. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3311. result.m[3] = 0.0;
  3312. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3313. result.m[5] = (axis.y * axis.y) * c1 + c;
  3314. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3315. result.m[7] = 0.0;
  3316. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3317. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3318. result.m[10] = (axis.z * axis.z) * c1 + c;
  3319. result.m[11] = 0.0;
  3320. result.m[15] = 1.0;
  3321. };
  3322. /**
  3323. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3324. */
  3325. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3326. var result = new Matrix();
  3327. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3328. return result;
  3329. };
  3330. /**
  3331. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3332. */
  3333. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3334. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3335. this._tempQuaternion.toRotationMatrix(result);
  3336. };
  3337. /**
  3338. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3339. */
  3340. Matrix.Scaling = function (x, y, z) {
  3341. var result = Matrix.Zero();
  3342. Matrix.ScalingToRef(x, y, z, result);
  3343. return result;
  3344. };
  3345. /**
  3346. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3347. */
  3348. Matrix.ScalingToRef = function (x, y, z, result) {
  3349. result.m[0] = x;
  3350. result.m[1] = 0.0;
  3351. result.m[2] = 0.0;
  3352. result.m[3] = 0.0;
  3353. result.m[4] = 0.0;
  3354. result.m[5] = y;
  3355. result.m[6] = 0.0;
  3356. result.m[7] = 0.0;
  3357. result.m[8] = 0.0;
  3358. result.m[9] = 0.0;
  3359. result.m[10] = z;
  3360. result.m[11] = 0.0;
  3361. result.m[12] = 0.0;
  3362. result.m[13] = 0.0;
  3363. result.m[14] = 0.0;
  3364. result.m[15] = 1.0;
  3365. };
  3366. /**
  3367. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3368. */
  3369. Matrix.Translation = function (x, y, z) {
  3370. var result = Matrix.Identity();
  3371. Matrix.TranslationToRef(x, y, z, result);
  3372. return result;
  3373. };
  3374. /**
  3375. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3376. */
  3377. Matrix.TranslationToRef = function (x, y, z, result) {
  3378. 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);
  3379. };
  3380. /**
  3381. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3382. */
  3383. Matrix.Lerp = function (startValue, endValue, gradient) {
  3384. var result = Matrix.Zero();
  3385. for (var index = 0; index < 16; index++) {
  3386. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3387. }
  3388. return result;
  3389. };
  3390. /**
  3391. * Returns a new Matrix whose values are computed by :
  3392. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3393. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3394. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3395. */
  3396. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3397. var startScale = new Vector3(0, 0, 0);
  3398. var startRotation = new Quaternion();
  3399. var startTranslation = new Vector3(0, 0, 0);
  3400. startValue.decompose(startScale, startRotation, startTranslation);
  3401. var endScale = new Vector3(0, 0, 0);
  3402. var endRotation = new Quaternion();
  3403. var endTranslation = new Vector3(0, 0, 0);
  3404. endValue.decompose(endScale, endRotation, endTranslation);
  3405. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3406. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3407. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3408. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3409. };
  3410. /**
  3411. * 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".
  3412. * This methods works for a Left-Handed system.
  3413. */
  3414. Matrix.LookAtLH = function (eye, target, up) {
  3415. var result = Matrix.Zero();
  3416. Matrix.LookAtLHToRef(eye, target, up, result);
  3417. return result;
  3418. };
  3419. /**
  3420. * 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".
  3421. * This methods works for a Left-Handed system.
  3422. */
  3423. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3424. // Z axis
  3425. target.subtractToRef(eye, this._zAxis);
  3426. this._zAxis.normalize();
  3427. // X axis
  3428. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3429. if (this._xAxis.lengthSquared() === 0) {
  3430. this._xAxis.x = 1.0;
  3431. }
  3432. else {
  3433. this._xAxis.normalize();
  3434. }
  3435. // Y axis
  3436. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3437. this._yAxis.normalize();
  3438. // Eye angles
  3439. var ex = -Vector3.Dot(this._xAxis, eye);
  3440. var ey = -Vector3.Dot(this._yAxis, eye);
  3441. var ez = -Vector3.Dot(this._zAxis, eye);
  3442. 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);
  3443. };
  3444. /**
  3445. * 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".
  3446. * This methods works for a Right-Handed system.
  3447. */
  3448. Matrix.LookAtRH = function (eye, target, up) {
  3449. var result = Matrix.Zero();
  3450. Matrix.LookAtRHToRef(eye, target, up, result);
  3451. return result;
  3452. };
  3453. /**
  3454. * 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".
  3455. * This methods works for a Left-Handed system.
  3456. */
  3457. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3458. // Z axis
  3459. eye.subtractToRef(target, this._zAxis);
  3460. this._zAxis.normalize();
  3461. // X axis
  3462. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3463. if (this._xAxis.lengthSquared() === 0) {
  3464. this._xAxis.x = 1.0;
  3465. }
  3466. else {
  3467. this._xAxis.normalize();
  3468. }
  3469. // Y axis
  3470. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3471. this._yAxis.normalize();
  3472. // Eye angles
  3473. var ex = -Vector3.Dot(this._xAxis, eye);
  3474. var ey = -Vector3.Dot(this._yAxis, eye);
  3475. var ez = -Vector3.Dot(this._zAxis, eye);
  3476. 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);
  3477. };
  3478. /**
  3479. * 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.
  3480. */
  3481. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3482. var matrix = Matrix.Zero();
  3483. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3484. return matrix;
  3485. };
  3486. /**
  3487. * 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.
  3488. */
  3489. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3490. var n = znear;
  3491. var f = zfar;
  3492. var a = 2.0 / width;
  3493. var b = 2.0 / height;
  3494. var c = 2.0 / (f - n);
  3495. var d = -(f + n) / (f - n);
  3496. 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);
  3497. };
  3498. /**
  3499. * 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.
  3500. */
  3501. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3502. var matrix = Matrix.Zero();
  3503. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3504. return matrix;
  3505. };
  3506. /**
  3507. * 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.
  3508. */
  3509. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3510. var n = znear;
  3511. var f = zfar;
  3512. var a = 2.0 / (right - left);
  3513. var b = 2.0 / (top - bottom);
  3514. var c = 2.0 / (f - n);
  3515. var d = -(f + n) / (f - n);
  3516. var i0 = (left + right) / (left - right);
  3517. var i1 = (top + bottom) / (bottom - top);
  3518. 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);
  3519. };
  3520. /**
  3521. * 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.
  3522. */
  3523. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3524. var matrix = Matrix.Zero();
  3525. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3526. return matrix;
  3527. };
  3528. /**
  3529. * 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.
  3530. */
  3531. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3532. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3533. result.m[10] *= -1.0;
  3534. };
  3535. /**
  3536. * 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.
  3537. */
  3538. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3539. var matrix = Matrix.Zero();
  3540. var n = znear;
  3541. var f = zfar;
  3542. var a = 2.0 * n / width;
  3543. var b = 2.0 * n / height;
  3544. var c = (f + n) / (f - n);
  3545. var d = -2.0 * f * n / (f - n);
  3546. 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);
  3547. return matrix;
  3548. };
  3549. /**
  3550. * 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.
  3551. */
  3552. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3553. var matrix = Matrix.Zero();
  3554. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3555. return matrix;
  3556. };
  3557. /**
  3558. * 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.
  3559. */
  3560. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3561. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3562. var n = znear;
  3563. var f = zfar;
  3564. var t = 1.0 / (Math.tan(fov * 0.5));
  3565. var a = isVerticalFovFixed ? (t / aspect) : t;
  3566. var b = isVerticalFovFixed ? t : (t * aspect);
  3567. var c = (f + n) / (f - n);
  3568. var d = -2.0 * f * n / (f - n);
  3569. 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);
  3570. };
  3571. /**
  3572. * 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.
  3573. */
  3574. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3575. var matrix = Matrix.Zero();
  3576. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3577. return matrix;
  3578. };
  3579. /**
  3580. * 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.
  3581. */
  3582. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3583. //alternatively this could be expressed as:
  3584. // m = PerspectiveFovLHToRef
  3585. // m[10] *= -1.0;
  3586. // m[11] *= -1.0;
  3587. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3588. var n = znear;
  3589. var f = zfar;
  3590. var t = 1.0 / (Math.tan(fov * 0.5));
  3591. var a = isVerticalFovFixed ? (t / aspect) : t;
  3592. var b = isVerticalFovFixed ? t : (t * aspect);
  3593. var c = -(f + n) / (f - n);
  3594. var d = -2 * f * n / (f - n);
  3595. 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);
  3596. };
  3597. /**
  3598. * 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.
  3599. */
  3600. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3601. if (rightHanded === void 0) { rightHanded = false; }
  3602. var rightHandedFactor = rightHanded ? -1 : 1;
  3603. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3604. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3605. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3606. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3607. var xScale = 2.0 / (leftTan + rightTan);
  3608. var yScale = 2.0 / (upTan + downTan);
  3609. result.m[0] = xScale;
  3610. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3611. result.m[5] = yScale;
  3612. result.m[6] = result.m[7] = 0.0;
  3613. result.m[8] = ((leftTan - rightTan) * xScale * 0.5) * rightHandedFactor;
  3614. result.m[9] = -((upTan - downTan) * yScale * 0.5) * rightHandedFactor;
  3615. result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3616. // result.m[10] = -zfar / (znear - zfar);
  3617. result.m[11] = 1.0 * rightHandedFactor;
  3618. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3619. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3620. // result.m[14] = (znear * zfar) / (znear - zfar);
  3621. };
  3622. /**
  3623. * Returns the final transformation matrix : world * view * projection * viewport
  3624. */
  3625. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3626. var cw = viewport.width;
  3627. var ch = viewport.height;
  3628. var cx = viewport.x;
  3629. var cy = viewport.y;
  3630. 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);
  3631. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3632. };
  3633. /**
  3634. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3635. */
  3636. Matrix.GetAsMatrix2x2 = function (matrix) {
  3637. return new Float32Array([
  3638. matrix.m[0], matrix.m[1],
  3639. matrix.m[4], matrix.m[5]
  3640. ]);
  3641. };
  3642. /**
  3643. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3644. */
  3645. Matrix.GetAsMatrix3x3 = function (matrix) {
  3646. return new Float32Array([
  3647. matrix.m[0], matrix.m[1], matrix.m[2],
  3648. matrix.m[4], matrix.m[5], matrix.m[6],
  3649. matrix.m[8], matrix.m[9], matrix.m[10]
  3650. ]);
  3651. };
  3652. /**
  3653. * Compute the transpose of the passed Matrix.
  3654. * Returns a new Matrix.
  3655. */
  3656. Matrix.Transpose = function (matrix) {
  3657. var result = new Matrix();
  3658. result.m[0] = matrix.m[0];
  3659. result.m[1] = matrix.m[4];
  3660. result.m[2] = matrix.m[8];
  3661. result.m[3] = matrix.m[12];
  3662. result.m[4] = matrix.m[1];
  3663. result.m[5] = matrix.m[5];
  3664. result.m[6] = matrix.m[9];
  3665. result.m[7] = matrix.m[13];
  3666. result.m[8] = matrix.m[2];
  3667. result.m[9] = matrix.m[6];
  3668. result.m[10] = matrix.m[10];
  3669. result.m[11] = matrix.m[14];
  3670. result.m[12] = matrix.m[3];
  3671. result.m[13] = matrix.m[7];
  3672. result.m[14] = matrix.m[11];
  3673. result.m[15] = matrix.m[15];
  3674. return result;
  3675. };
  3676. /**
  3677. * Returns a new Matrix as the reflection matrix across the passed plane.
  3678. */
  3679. Matrix.Reflection = function (plane) {
  3680. var matrix = new Matrix();
  3681. Matrix.ReflectionToRef(plane, matrix);
  3682. return matrix;
  3683. };
  3684. /**
  3685. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3686. */
  3687. Matrix.ReflectionToRef = function (plane, result) {
  3688. plane.normalize();
  3689. var x = plane.normal.x;
  3690. var y = plane.normal.y;
  3691. var z = plane.normal.z;
  3692. var temp = -2 * x;
  3693. var temp2 = -2 * y;
  3694. var temp3 = -2 * z;
  3695. result.m[0] = (temp * x) + 1;
  3696. result.m[1] = temp2 * x;
  3697. result.m[2] = temp3 * x;
  3698. result.m[3] = 0.0;
  3699. result.m[4] = temp * y;
  3700. result.m[5] = (temp2 * y) + 1;
  3701. result.m[6] = temp3 * y;
  3702. result.m[7] = 0.0;
  3703. result.m[8] = temp * z;
  3704. result.m[9] = temp2 * z;
  3705. result.m[10] = (temp3 * z) + 1;
  3706. result.m[11] = 0.0;
  3707. result.m[12] = temp * plane.d;
  3708. result.m[13] = temp2 * plane.d;
  3709. result.m[14] = temp3 * plane.d;
  3710. result.m[15] = 1.0;
  3711. };
  3712. /**
  3713. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3714. */
  3715. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  3716. mat.m[0] = xaxis.x;
  3717. mat.m[1] = xaxis.y;
  3718. mat.m[2] = xaxis.z;
  3719. mat.m[3] = 0.0;
  3720. mat.m[4] = yaxis.x;
  3721. mat.m[5] = yaxis.y;
  3722. mat.m[6] = yaxis.z;
  3723. mat.m[7] = 0.0;
  3724. mat.m[8] = zaxis.x;
  3725. mat.m[9] = zaxis.y;
  3726. mat.m[10] = zaxis.z;
  3727. mat.m[11] = 0.0;
  3728. mat.m[12] = 0.0;
  3729. mat.m[13] = 0.0;
  3730. mat.m[14] = 0.0;
  3731. mat.m[15] = 1.0;
  3732. };
  3733. /**
  3734. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3735. */
  3736. Matrix.FromQuaternionToRef = function (quat, result) {
  3737. var xx = quat.x * quat.x;
  3738. var yy = quat.y * quat.y;
  3739. var zz = quat.z * quat.z;
  3740. var xy = quat.x * quat.y;
  3741. var zw = quat.z * quat.w;
  3742. var zx = quat.z * quat.x;
  3743. var yw = quat.y * quat.w;
  3744. var yz = quat.y * quat.z;
  3745. var xw = quat.x * quat.w;
  3746. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3747. result.m[1] = 2.0 * (xy + zw);
  3748. result.m[2] = 2.0 * (zx - yw);
  3749. result.m[3] = 0.0;
  3750. result.m[4] = 2.0 * (xy - zw);
  3751. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3752. result.m[6] = 2.0 * (yz + xw);
  3753. result.m[7] = 0.0;
  3754. result.m[8] = 2.0 * (zx + yw);
  3755. result.m[9] = 2.0 * (yz - xw);
  3756. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3757. result.m[11] = 0.0;
  3758. result.m[12] = 0.0;
  3759. result.m[13] = 0.0;
  3760. result.m[14] = 0.0;
  3761. result.m[15] = 1.0;
  3762. };
  3763. return Matrix;
  3764. }());
  3765. Matrix._tempQuaternion = new Quaternion();
  3766. Matrix._xAxis = Vector3.Zero();
  3767. Matrix._yAxis = Vector3.Zero();
  3768. Matrix._zAxis = Vector3.Zero();
  3769. BABYLON.Matrix = Matrix;
  3770. var Plane = (function () {
  3771. /**
  3772. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3773. */
  3774. function Plane(a, b, c, d) {
  3775. this.normal = new Vector3(a, b, c);
  3776. this.d = d;
  3777. }
  3778. /**
  3779. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3780. */
  3781. Plane.prototype.asArray = function () {
  3782. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3783. };
  3784. // Methods
  3785. /**
  3786. * Returns a new plane copied from the current Plane.
  3787. */
  3788. Plane.prototype.clone = function () {
  3789. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3790. };
  3791. /**
  3792. * Returns the string "Plane".
  3793. */
  3794. Plane.prototype.getClassName = function () {
  3795. return "Plane";
  3796. };
  3797. /**
  3798. * Returns the Plane hash code.
  3799. */
  3800. Plane.prototype.getHashCode = function () {
  3801. var hash = this.normal.getHashCode();
  3802. hash = (hash * 397) ^ (this.d || 0);
  3803. return hash;
  3804. };
  3805. /**
  3806. * Normalize the current Plane in place.
  3807. * Returns the updated Plane.
  3808. */
  3809. Plane.prototype.normalize = function () {
  3810. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3811. var magnitude = 0.0;
  3812. if (norm !== 0) {
  3813. magnitude = 1.0 / norm;
  3814. }
  3815. this.normal.x *= magnitude;
  3816. this.normal.y *= magnitude;
  3817. this.normal.z *= magnitude;
  3818. this.d *= magnitude;
  3819. return this;
  3820. };
  3821. /**
  3822. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3823. */
  3824. Plane.prototype.transform = function (transformation) {
  3825. var transposedMatrix = Matrix.Transpose(transformation);
  3826. var x = this.normal.x;
  3827. var y = this.normal.y;
  3828. var z = this.normal.z;
  3829. var d = this.d;
  3830. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3831. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3832. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3833. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3834. return new Plane(normalX, normalY, normalZ, finalD);
  3835. };
  3836. /**
  3837. * Returns the dot product (float) of the point coordinates and the plane normal.
  3838. */
  3839. Plane.prototype.dotCoordinate = function (point) {
  3840. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3841. };
  3842. /**
  3843. * Updates the current Plane from the plane defined by the three passed points.
  3844. * Returns the updated Plane.
  3845. */
  3846. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3847. var x1 = point2.x - point1.x;
  3848. var y1 = point2.y - point1.y;
  3849. var z1 = point2.z - point1.z;
  3850. var x2 = point3.x - point1.x;
  3851. var y2 = point3.y - point1.y;
  3852. var z2 = point3.z - point1.z;
  3853. var yz = (y1 * z2) - (z1 * y2);
  3854. var xz = (z1 * x2) - (x1 * z2);
  3855. var xy = (x1 * y2) - (y1 * x2);
  3856. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3857. var invPyth;
  3858. if (pyth !== 0) {
  3859. invPyth = 1.0 / pyth;
  3860. }
  3861. else {
  3862. invPyth = 0.0;
  3863. }
  3864. this.normal.x = yz * invPyth;
  3865. this.normal.y = xz * invPyth;
  3866. this.normal.z = xy * invPyth;
  3867. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3868. return this;
  3869. };
  3870. /**
  3871. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3872. */
  3873. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3874. var dot = Vector3.Dot(this.normal, direction);
  3875. return (dot <= epsilon);
  3876. };
  3877. /**
  3878. * Returns the signed distance (float) from the passed point to the Plane.
  3879. */
  3880. Plane.prototype.signedDistanceTo = function (point) {
  3881. return Vector3.Dot(point, this.normal) + this.d;
  3882. };
  3883. // Statics
  3884. /**
  3885. * Returns a new Plane from the passed array.
  3886. */
  3887. Plane.FromArray = function (array) {
  3888. return new Plane(array[0], array[1], array[2], array[3]);
  3889. };
  3890. /**
  3891. * Returns a new Plane defined by the three passed points.
  3892. */
  3893. Plane.FromPoints = function (point1, point2, point3) {
  3894. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3895. result.copyFromPoints(point1, point2, point3);
  3896. return result;
  3897. };
  3898. /**
  3899. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3900. * Note : the vector "normal" is updated because normalized.
  3901. */
  3902. Plane.FromPositionAndNormal = function (origin, normal) {
  3903. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3904. normal.normalize();
  3905. result.normal = normal;
  3906. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3907. return result;
  3908. };
  3909. /**
  3910. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3911. */
  3912. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3913. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3914. return Vector3.Dot(point, normal) + d;
  3915. };
  3916. return Plane;
  3917. }());
  3918. BABYLON.Plane = Plane;
  3919. var Viewport = (function () {
  3920. /**
  3921. * Creates a Viewport object located at (x, y) and sized (width, height).
  3922. */
  3923. function Viewport(x, y, width, height) {
  3924. this.x = x;
  3925. this.y = y;
  3926. this.width = width;
  3927. this.height = height;
  3928. }
  3929. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3930. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3931. };
  3932. /**
  3933. * Returns a new Viewport copied from the current one.
  3934. */
  3935. Viewport.prototype.clone = function () {
  3936. return new Viewport(this.x, this.y, this.width, this.height);
  3937. };
  3938. return Viewport;
  3939. }());
  3940. BABYLON.Viewport = Viewport;
  3941. var Frustum = (function () {
  3942. function Frustum() {
  3943. }
  3944. /**
  3945. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  3946. */
  3947. Frustum.GetPlanes = function (transform) {
  3948. var frustumPlanes = [];
  3949. for (var index = 0; index < 6; index++) {
  3950. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  3951. }
  3952. Frustum.GetPlanesToRef(transform, frustumPlanes);
  3953. return frustumPlanes;
  3954. };
  3955. /**
  3956. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  3957. */
  3958. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  3959. // Near
  3960. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  3961. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  3962. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  3963. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  3964. frustumPlanes[0].normalize();
  3965. // Far
  3966. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  3967. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  3968. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  3969. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  3970. frustumPlanes[1].normalize();
  3971. // Left
  3972. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  3973. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  3974. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  3975. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  3976. frustumPlanes[2].normalize();
  3977. // Right
  3978. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  3979. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  3980. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  3981. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  3982. frustumPlanes[3].normalize();
  3983. // Top
  3984. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  3985. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  3986. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  3987. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  3988. frustumPlanes[4].normalize();
  3989. // Bottom
  3990. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  3991. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  3992. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  3993. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  3994. frustumPlanes[5].normalize();
  3995. };
  3996. return Frustum;
  3997. }());
  3998. BABYLON.Frustum = Frustum;
  3999. var Space;
  4000. (function (Space) {
  4001. Space[Space["LOCAL"] = 0] = "LOCAL";
  4002. Space[Space["WORLD"] = 1] = "WORLD";
  4003. Space[Space["BONE"] = 2] = "BONE";
  4004. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4005. var Axis = (function () {
  4006. function Axis() {
  4007. }
  4008. return Axis;
  4009. }());
  4010. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4011. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4012. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4013. BABYLON.Axis = Axis;
  4014. ;
  4015. var BezierCurve = (function () {
  4016. function BezierCurve() {
  4017. }
  4018. /**
  4019. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4020. */
  4021. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4022. // Extract X (which is equal to time here)
  4023. var f0 = 1 - 3 * x2 + 3 * x1;
  4024. var f1 = 3 * x2 - 6 * x1;
  4025. var f2 = 3 * x1;
  4026. var refinedT = t;
  4027. for (var i = 0; i < 5; i++) {
  4028. var refinedT2 = refinedT * refinedT;
  4029. var refinedT3 = refinedT2 * refinedT;
  4030. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4031. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4032. refinedT -= (x - t) * slope;
  4033. refinedT = Math.min(1, Math.max(0, refinedT));
  4034. }
  4035. // Resolve cubic bezier for the given x
  4036. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4037. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4038. Math.pow(refinedT, 3);
  4039. };
  4040. return BezierCurve;
  4041. }());
  4042. BABYLON.BezierCurve = BezierCurve;
  4043. var Orientation;
  4044. (function (Orientation) {
  4045. Orientation[Orientation["CW"] = 0] = "CW";
  4046. Orientation[Orientation["CCW"] = 1] = "CCW";
  4047. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4048. var Angle = (function () {
  4049. /**
  4050. * Creates an Angle object of "radians" radians (float).
  4051. */
  4052. function Angle(radians) {
  4053. var _this = this;
  4054. /**
  4055. * Returns the Angle value in degrees (float).
  4056. */
  4057. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4058. /**
  4059. * Returns the Angle value in radians (float).
  4060. */
  4061. this.radians = function () { return _this._radians; };
  4062. this._radians = radians;
  4063. if (this._radians < 0.0)
  4064. this._radians += (2.0 * Math.PI);
  4065. }
  4066. /**
  4067. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4068. */
  4069. Angle.BetweenTwoPoints = function (a, b) {
  4070. var delta = b.subtract(a);
  4071. var theta = Math.atan2(delta.y, delta.x);
  4072. return new Angle(theta);
  4073. };
  4074. /**
  4075. * Returns a new Angle object from the passed float in radians.
  4076. */
  4077. Angle.FromRadians = function (radians) {
  4078. return new Angle(radians);
  4079. };
  4080. /**
  4081. * Returns a new Angle object from the passed float in degrees.
  4082. */
  4083. Angle.FromDegrees = function (degrees) {
  4084. return new Angle(degrees * Math.PI / 180.0);
  4085. };
  4086. return Angle;
  4087. }());
  4088. BABYLON.Angle = Angle;
  4089. var Arc2 = (function () {
  4090. /**
  4091. * Creates an Arc object from the three passed points : start, middle and end.
  4092. */
  4093. function Arc2(startPoint, midPoint, endPoint) {
  4094. this.startPoint = startPoint;
  4095. this.midPoint = midPoint;
  4096. this.endPoint = endPoint;
  4097. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4098. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4099. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4100. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4101. 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);
  4102. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4103. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4104. var a1 = this.startAngle.degrees();
  4105. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4106. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4107. // angles correction
  4108. if (a2 - a1 > +180.0)
  4109. a2 -= 360.0;
  4110. if (a2 - a1 < -180.0)
  4111. a2 += 360.0;
  4112. if (a3 - a2 > +180.0)
  4113. a3 -= 360.0;
  4114. if (a3 - a2 < -180.0)
  4115. a3 += 360.0;
  4116. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4117. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4118. }
  4119. return Arc2;
  4120. }());
  4121. BABYLON.Arc2 = Arc2;
  4122. var Path2 = (function () {
  4123. /**
  4124. * Creates a Path2 object from the starting 2D coordinates x and y.
  4125. */
  4126. function Path2(x, y) {
  4127. this._points = new Array();
  4128. this._length = 0.0;
  4129. this.closed = false;
  4130. this._points.push(new Vector2(x, y));
  4131. }
  4132. /**
  4133. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4134. * Returns the updated Path2.
  4135. */
  4136. Path2.prototype.addLineTo = function (x, y) {
  4137. if (closed) {
  4138. //Tools.Error("cannot add lines to closed paths");
  4139. return this;
  4140. }
  4141. var newPoint = new Vector2(x, y);
  4142. var previousPoint = this._points[this._points.length - 1];
  4143. this._points.push(newPoint);
  4144. this._length += newPoint.subtract(previousPoint).length();
  4145. return this;
  4146. };
  4147. /**
  4148. * 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.
  4149. * Returns the updated Path2.
  4150. */
  4151. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4152. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4153. if (closed) {
  4154. //Tools.Error("cannot add arcs to closed paths");
  4155. return this;
  4156. }
  4157. var startPoint = this._points[this._points.length - 1];
  4158. var midPoint = new Vector2(midX, midY);
  4159. var endPoint = new Vector2(endX, endY);
  4160. var arc = new Arc2(startPoint, midPoint, endPoint);
  4161. var increment = arc.angle.radians() / numberOfSegments;
  4162. if (arc.orientation === Orientation.CW)
  4163. increment *= -1;
  4164. var currentAngle = arc.startAngle.radians() + increment;
  4165. for (var i = 0; i < numberOfSegments; i++) {
  4166. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4167. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4168. this.addLineTo(x, y);
  4169. currentAngle += increment;
  4170. }
  4171. return this;
  4172. };
  4173. /**
  4174. * Closes the Path2.
  4175. * Returns the Path2.
  4176. */
  4177. Path2.prototype.close = function () {
  4178. this.closed = true;
  4179. return this;
  4180. };
  4181. /**
  4182. * Returns the Path2 total length (float).
  4183. */
  4184. Path2.prototype.length = function () {
  4185. var result = this._length;
  4186. if (!this.closed) {
  4187. var lastPoint = this._points[this._points.length - 1];
  4188. var firstPoint = this._points[0];
  4189. result += (firstPoint.subtract(lastPoint).length());
  4190. }
  4191. return result;
  4192. };
  4193. /**
  4194. * Returns the Path2 internal array of points.
  4195. */
  4196. Path2.prototype.getPoints = function () {
  4197. return this._points;
  4198. };
  4199. /**
  4200. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4201. */
  4202. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4203. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4204. //Tools.Error("normalized length position should be between 0 and 1.");
  4205. return Vector2.Zero();
  4206. }
  4207. var lengthPosition = normalizedLengthPosition * this.length();
  4208. var previousOffset = 0;
  4209. for (var i = 0; i < this._points.length; i++) {
  4210. var j = (i + 1) % this._points.length;
  4211. var a = this._points[i];
  4212. var b = this._points[j];
  4213. var bToA = b.subtract(a);
  4214. var nextOffset = (bToA.length() + previousOffset);
  4215. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4216. var dir = bToA.normalize();
  4217. var localOffset = lengthPosition - previousOffset;
  4218. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4219. }
  4220. previousOffset = nextOffset;
  4221. }
  4222. //Tools.Error("internal error");
  4223. return Vector2.Zero();
  4224. };
  4225. /**
  4226. * Returns a new Path2 starting at the coordinates (x, y).
  4227. */
  4228. Path2.StartingAt = function (x, y) {
  4229. return new Path2(x, y);
  4230. };
  4231. return Path2;
  4232. }());
  4233. BABYLON.Path2 = Path2;
  4234. var Path3D = (function () {
  4235. /**
  4236. * new Path3D(path, normal, raw)
  4237. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4238. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4239. * path : an array of Vector3, the curve axis of the Path3D
  4240. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4241. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4242. */
  4243. function Path3D(path, firstNormal, raw) {
  4244. this.path = path;
  4245. this._curve = new Array();
  4246. this._distances = new Array();
  4247. this._tangents = new Array();
  4248. this._normals = new Array();
  4249. this._binormals = new Array();
  4250. for (var p = 0; p < path.length; p++) {
  4251. this._curve[p] = path[p].clone(); // hard copy
  4252. }
  4253. this._raw = raw || false;
  4254. this._compute(firstNormal);
  4255. }
  4256. /**
  4257. * Returns the Path3D array of successive Vector3 designing its curve.
  4258. */
  4259. Path3D.prototype.getCurve = function () {
  4260. return this._curve;
  4261. };
  4262. /**
  4263. * Returns an array populated with tangent vectors on each Path3D curve point.
  4264. */
  4265. Path3D.prototype.getTangents = function () {
  4266. return this._tangents;
  4267. };
  4268. /**
  4269. * Returns an array populated with normal vectors on each Path3D curve point.
  4270. */
  4271. Path3D.prototype.getNormals = function () {
  4272. return this._normals;
  4273. };
  4274. /**
  4275. * Returns an array populated with binormal vectors on each Path3D curve point.
  4276. */
  4277. Path3D.prototype.getBinormals = function () {
  4278. return this._binormals;
  4279. };
  4280. /**
  4281. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4282. */
  4283. Path3D.prototype.getDistances = function () {
  4284. return this._distances;
  4285. };
  4286. /**
  4287. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4288. * Returns the same object updated.
  4289. */
  4290. Path3D.prototype.update = function (path, firstNormal) {
  4291. for (var p = 0; p < path.length; p++) {
  4292. this._curve[p].x = path[p].x;
  4293. this._curve[p].y = path[p].y;
  4294. this._curve[p].z = path[p].z;
  4295. }
  4296. this._compute(firstNormal);
  4297. return this;
  4298. };
  4299. // private function compute() : computes tangents, normals and binormals
  4300. Path3D.prototype._compute = function (firstNormal) {
  4301. var l = this._curve.length;
  4302. // first and last tangents
  4303. this._tangents[0] = this._getFirstNonNullVector(0);
  4304. if (!this._raw) {
  4305. this._tangents[0].normalize();
  4306. }
  4307. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4308. if (!this._raw) {
  4309. this._tangents[l - 1].normalize();
  4310. }
  4311. // normals and binormals at first point : arbitrary vector with _normalVector()
  4312. var tg0 = this._tangents[0];
  4313. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4314. this._normals[0] = pp0;
  4315. if (!this._raw) {
  4316. this._normals[0].normalize();
  4317. }
  4318. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4319. if (!this._raw) {
  4320. this._binormals[0].normalize();
  4321. }
  4322. this._distances[0] = 0.0;
  4323. // normals and binormals : next points
  4324. var prev; // previous vector (segment)
  4325. var cur; // current vector (segment)
  4326. var curTang; // current tangent
  4327. // previous normal
  4328. var prevBinor; // previous binormal
  4329. for (var i = 1; i < l; i++) {
  4330. // tangents
  4331. prev = this._getLastNonNullVector(i);
  4332. if (i < l - 1) {
  4333. cur = this._getFirstNonNullVector(i);
  4334. this._tangents[i] = prev.add(cur);
  4335. this._tangents[i].normalize();
  4336. }
  4337. this._distances[i] = this._distances[i - 1] + prev.length();
  4338. // normals and binormals
  4339. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4340. curTang = this._tangents[i];
  4341. prevBinor = this._binormals[i - 1];
  4342. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4343. if (!this._raw) {
  4344. this._normals[i].normalize();
  4345. }
  4346. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4347. if (!this._raw) {
  4348. this._binormals[i].normalize();
  4349. }
  4350. }
  4351. };
  4352. // private function getFirstNonNullVector(index)
  4353. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4354. Path3D.prototype._getFirstNonNullVector = function (index) {
  4355. var i = 1;
  4356. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4357. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4358. i++;
  4359. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4360. }
  4361. return nNVector;
  4362. };
  4363. // private function getLastNonNullVector(index)
  4364. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4365. Path3D.prototype._getLastNonNullVector = function (index) {
  4366. var i = 1;
  4367. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4368. while (nLVector.length() === 0 && index > i + 1) {
  4369. i++;
  4370. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4371. }
  4372. return nLVector;
  4373. };
  4374. // private function normalVector(v0, vt, va) :
  4375. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4376. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4377. Path3D.prototype._normalVector = function (v0, vt, va) {
  4378. var normal0;
  4379. var tgl = vt.length();
  4380. if (tgl === 0.0) {
  4381. tgl = 1.0;
  4382. }
  4383. if (va === undefined || va === null) {
  4384. var point;
  4385. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4386. point = new Vector3(0.0, -1.0, 0.0);
  4387. }
  4388. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4389. point = new Vector3(1.0, 0.0, 0.0);
  4390. }
  4391. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4392. point = new Vector3(0.0, 0.0, 1.0);
  4393. }
  4394. normal0 = Vector3.Cross(vt, point);
  4395. }
  4396. else {
  4397. normal0 = Vector3.Cross(vt, va);
  4398. Vector3.CrossToRef(normal0, vt, normal0);
  4399. }
  4400. normal0.normalize();
  4401. return normal0;
  4402. };
  4403. return Path3D;
  4404. }());
  4405. BABYLON.Path3D = Path3D;
  4406. var Curve3 = (function () {
  4407. /**
  4408. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4409. * A Curve3 is designed from a series of successive Vector3.
  4410. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4411. */
  4412. function Curve3(points) {
  4413. this._length = 0.0;
  4414. this._points = points;
  4415. this._length = this._computeLength(points);
  4416. }
  4417. /**
  4418. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4419. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4420. * @param v1 (Vector3) the control point
  4421. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4422. * @param nbPoints (integer) the wanted number of points in the curve
  4423. */
  4424. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4425. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4426. var bez = new Array();
  4427. var equation = function (t, val0, val1, val2) {
  4428. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4429. return res;
  4430. };
  4431. for (var i = 0; i <= nbPoints; i++) {
  4432. 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)));
  4433. }
  4434. return new Curve3(bez);
  4435. };
  4436. /**
  4437. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4438. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4439. * @param v1 (Vector3) the first control point
  4440. * @param v2 (Vector3) the second control point
  4441. * @param v3 (Vector3) the end point of the Cubic Bezier
  4442. * @param nbPoints (integer) the wanted number of points in the curve
  4443. */
  4444. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4445. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4446. var bez = new Array();
  4447. var equation = function (t, val0, val1, val2, val3) {
  4448. 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;
  4449. return res;
  4450. };
  4451. for (var i = 0; i <= nbPoints; i++) {
  4452. 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)));
  4453. }
  4454. return new Curve3(bez);
  4455. };
  4456. /**
  4457. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4458. * @param p1 (Vector3) the origin point of the Hermite Spline
  4459. * @param t1 (Vector3) the tangent vector at the origin point
  4460. * @param p2 (Vector3) the end point of the Hermite Spline
  4461. * @param t2 (Vector3) the tangent vector at the end point
  4462. * @param nbPoints (integer) the wanted number of points in the curve
  4463. */
  4464. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4465. var hermite = new Array();
  4466. var step = 1.0 / nbPoints;
  4467. for (var i = 0; i <= nbPoints; i++) {
  4468. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4469. }
  4470. return new Curve3(hermite);
  4471. };
  4472. /**
  4473. * Returns a Curve3 object along a CatmullRom Spline curve :
  4474. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4475. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4476. */
  4477. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4478. var totalPoints = new Array();
  4479. totalPoints.push(points[0].clone());
  4480. Array.prototype.push.apply(totalPoints, points);
  4481. totalPoints.push(points[points.length - 1].clone());
  4482. var catmullRom = new Array();
  4483. var step = 1.0 / nbPoints;
  4484. for (var i = 0; i < totalPoints.length - 3; i++) {
  4485. var amount = 0.0;
  4486. for (var c = 0; c < nbPoints; c++) {
  4487. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4488. amount += step;
  4489. }
  4490. }
  4491. i--;
  4492. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4493. return new Curve3(catmullRom);
  4494. };
  4495. /**
  4496. * Returns the Curve3 stored array of successive Vector3
  4497. */
  4498. Curve3.prototype.getPoints = function () {
  4499. return this._points;
  4500. };
  4501. /**
  4502. * Returns the computed length (float) of the curve.
  4503. */
  4504. Curve3.prototype.length = function () {
  4505. return this._length;
  4506. };
  4507. /**
  4508. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4509. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4510. * curveA and curveB keep unchanged.
  4511. */
  4512. Curve3.prototype.continue = function (curve) {
  4513. var lastPoint = this._points[this._points.length - 1];
  4514. var continuedPoints = this._points.slice();
  4515. var curvePoints = curve.getPoints();
  4516. for (var i = 1; i < curvePoints.length; i++) {
  4517. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4518. }
  4519. var continuedCurve = new Curve3(continuedPoints);
  4520. return continuedCurve;
  4521. };
  4522. Curve3.prototype._computeLength = function (path) {
  4523. var l = 0;
  4524. for (var i = 1; i < path.length; i++) {
  4525. l += (path[i].subtract(path[i - 1])).length();
  4526. }
  4527. return l;
  4528. };
  4529. return Curve3;
  4530. }());
  4531. BABYLON.Curve3 = Curve3;
  4532. // SphericalHarmonics
  4533. var SphericalHarmonics = (function () {
  4534. function SphericalHarmonics() {
  4535. this.L00 = Vector3.Zero();
  4536. this.L1_1 = Vector3.Zero();
  4537. this.L10 = Vector3.Zero();
  4538. this.L11 = Vector3.Zero();
  4539. this.L2_2 = Vector3.Zero();
  4540. this.L2_1 = Vector3.Zero();
  4541. this.L20 = Vector3.Zero();
  4542. this.L21 = Vector3.Zero();
  4543. this.L22 = Vector3.Zero();
  4544. }
  4545. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4546. var colorVector = new Vector3(color.r, color.g, color.b);
  4547. var c = colorVector.scale(deltaSolidAngle);
  4548. this.L00 = this.L00.add(c.scale(0.282095));
  4549. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4550. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4551. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4552. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4553. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4554. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4555. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4556. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4557. };
  4558. SphericalHarmonics.prototype.scale = function (scale) {
  4559. this.L00 = this.L00.scale(scale);
  4560. this.L1_1 = this.L1_1.scale(scale);
  4561. this.L10 = this.L10.scale(scale);
  4562. this.L11 = this.L11.scale(scale);
  4563. this.L2_2 = this.L2_2.scale(scale);
  4564. this.L2_1 = this.L2_1.scale(scale);
  4565. this.L20 = this.L20.scale(scale);
  4566. this.L21 = this.L21.scale(scale);
  4567. this.L22 = this.L22.scale(scale);
  4568. };
  4569. return SphericalHarmonics;
  4570. }());
  4571. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4572. // SphericalPolynomial
  4573. var SphericalPolynomial = (function () {
  4574. function SphericalPolynomial() {
  4575. this.x = Vector3.Zero();
  4576. this.y = Vector3.Zero();
  4577. this.z = Vector3.Zero();
  4578. this.xx = Vector3.Zero();
  4579. this.yy = Vector3.Zero();
  4580. this.zz = Vector3.Zero();
  4581. this.xy = Vector3.Zero();
  4582. this.yz = Vector3.Zero();
  4583. this.zx = Vector3.Zero();
  4584. }
  4585. SphericalPolynomial.prototype.addAmbient = function (color) {
  4586. var colorVector = new Vector3(color.r, color.g, color.b);
  4587. this.xx = this.xx.add(colorVector);
  4588. this.yy = this.yy.add(colorVector);
  4589. this.zz = this.zz.add(colorVector);
  4590. };
  4591. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4592. var result = new SphericalPolynomial();
  4593. result.x = harmonics.L11.scale(1.02333);
  4594. result.y = harmonics.L1_1.scale(1.02333);
  4595. result.z = harmonics.L10.scale(1.02333);
  4596. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4597. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4598. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4599. result.yz = harmonics.L2_1.scale(0.858086);
  4600. result.zx = harmonics.L21.scale(0.858086);
  4601. result.xy = harmonics.L2_2.scale(0.858086);
  4602. return result;
  4603. };
  4604. return SphericalPolynomial;
  4605. }());
  4606. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4607. // Vertex formats
  4608. var PositionNormalVertex = (function () {
  4609. function PositionNormalVertex(position, normal) {
  4610. if (position === void 0) { position = Vector3.Zero(); }
  4611. if (normal === void 0) { normal = Vector3.Up(); }
  4612. this.position = position;
  4613. this.normal = normal;
  4614. }
  4615. PositionNormalVertex.prototype.clone = function () {
  4616. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4617. };
  4618. return PositionNormalVertex;
  4619. }());
  4620. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4621. var PositionNormalTextureVertex = (function () {
  4622. function PositionNormalTextureVertex(position, normal, uv) {
  4623. if (position === void 0) { position = Vector3.Zero(); }
  4624. if (normal === void 0) { normal = Vector3.Up(); }
  4625. if (uv === void 0) { uv = Vector2.Zero(); }
  4626. this.position = position;
  4627. this.normal = normal;
  4628. this.uv = uv;
  4629. }
  4630. PositionNormalTextureVertex.prototype.clone = function () {
  4631. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4632. };
  4633. return PositionNormalTextureVertex;
  4634. }());
  4635. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4636. // Temporary pre-allocated objects for engine internal use
  4637. // usage in any internal function :
  4638. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4639. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4640. var Tmp = (function () {
  4641. function Tmp() {
  4642. }
  4643. return Tmp;
  4644. }());
  4645. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4646. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4647. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4648. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4649. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4650. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4651. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4652. Matrix.Zero(), Matrix.Zero(),
  4653. Matrix.Zero(), Matrix.Zero(),
  4654. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4655. BABYLON.Tmp = Tmp;
  4656. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4657. var MathTmp = (function () {
  4658. function MathTmp() {
  4659. }
  4660. return MathTmp;
  4661. }());
  4662. MathTmp.Vector3 = [Vector3.Zero()];
  4663. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4664. MathTmp.Quaternion = [Quaternion.Zero()];
  4665. })(BABYLON || (BABYLON = {}));
  4666. //# sourceMappingURL=babylon.math.js.map
  4667. //# sourceMappingURL=babylon.mixins.js.map
  4668. var BABYLON;
  4669. (function (BABYLON) {
  4670. function generateSerializableMember(type, sourceName) {
  4671. return function (target, propertyKey) {
  4672. if (!target.__serializableMembers) {
  4673. target.__serializableMembers = {};
  4674. }
  4675. if (!target.__serializableMembers[propertyKey]) {
  4676. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4677. }
  4678. };
  4679. }
  4680. function generateExpandMember(setCallback) {
  4681. return function (target, propertyKey) {
  4682. if (setCallback) {
  4683. var key = "_" + propertyKey;
  4684. Object.defineProperty(target, propertyKey, {
  4685. get: function () {
  4686. return this[key];
  4687. },
  4688. set: function (value) {
  4689. if (this[key] === value) {
  4690. return;
  4691. }
  4692. this[key] = value;
  4693. target[setCallback].apply(this);
  4694. },
  4695. enumerable: true,
  4696. configurable: true
  4697. });
  4698. }
  4699. };
  4700. }
  4701. function expandToProperty(callback) {
  4702. return generateExpandMember(callback);
  4703. }
  4704. BABYLON.expandToProperty = expandToProperty;
  4705. function serialize(sourceName) {
  4706. return generateSerializableMember(0, sourceName); // value member
  4707. }
  4708. BABYLON.serialize = serialize;
  4709. function serializeAsTexture(sourceName) {
  4710. return generateSerializableMember(1, sourceName); // texture member
  4711. }
  4712. BABYLON.serializeAsTexture = serializeAsTexture;
  4713. function serializeAsColor3(sourceName) {
  4714. return generateSerializableMember(2, sourceName); // color3 member
  4715. }
  4716. BABYLON.serializeAsColor3 = serializeAsColor3;
  4717. function serializeAsFresnelParameters(sourceName) {
  4718. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4719. }
  4720. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4721. function serializeAsVector2(sourceName) {
  4722. return generateSerializableMember(4, sourceName); // vector2 member
  4723. }
  4724. BABYLON.serializeAsVector2 = serializeAsVector2;
  4725. function serializeAsVector3(sourceName) {
  4726. return generateSerializableMember(5, sourceName); // vector3 member
  4727. }
  4728. BABYLON.serializeAsVector3 = serializeAsVector3;
  4729. function serializeAsMeshReference(sourceName) {
  4730. return generateSerializableMember(6, sourceName); // mesh reference member
  4731. }
  4732. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4733. function serializeAsColorCurves(sourceName) {
  4734. return generateSerializableMember(7, sourceName); // color curves
  4735. }
  4736. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4737. var SerializationHelper = (function () {
  4738. function SerializationHelper() {
  4739. }
  4740. SerializationHelper.Serialize = function (entity, serializationObject) {
  4741. if (!serializationObject) {
  4742. serializationObject = {};
  4743. }
  4744. // Tags
  4745. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4746. // Properties
  4747. for (var property in entity.__serializableMembers) {
  4748. var propertyDescriptor = entity.__serializableMembers[property];
  4749. var targetPropertyName = propertyDescriptor.sourceName || property;
  4750. var propertyType = propertyDescriptor.type;
  4751. var sourceProperty = entity[property];
  4752. if (sourceProperty !== undefined && sourceProperty !== null) {
  4753. switch (propertyType) {
  4754. case 0:
  4755. serializationObject[targetPropertyName] = sourceProperty;
  4756. break;
  4757. case 1:
  4758. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4759. break;
  4760. case 2:
  4761. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4762. break;
  4763. case 3:
  4764. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4765. break;
  4766. case 4:
  4767. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4768. break;
  4769. case 5:
  4770. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4771. break;
  4772. case 6:
  4773. serializationObject[targetPropertyName] = sourceProperty.id;
  4774. break;
  4775. case 7:
  4776. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4777. break;
  4778. }
  4779. }
  4780. }
  4781. return serializationObject;
  4782. };
  4783. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4784. var destination = creationFunction();
  4785. // Tags
  4786. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4787. // Properties
  4788. for (var property in destination.__serializableMembers) {
  4789. var propertyDescriptor = destination.__serializableMembers[property];
  4790. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4791. var propertyType = propertyDescriptor.type;
  4792. if (sourceProperty !== undefined && sourceProperty !== null) {
  4793. switch (propertyType) {
  4794. case 0:
  4795. destination[property] = sourceProperty;
  4796. break;
  4797. case 1:
  4798. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4799. break;
  4800. case 2:
  4801. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4802. break;
  4803. case 3:
  4804. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4805. break;
  4806. case 4:
  4807. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4808. break;
  4809. case 5:
  4810. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4811. break;
  4812. case 6:
  4813. destination[property] = scene.getLastMeshByID(sourceProperty);
  4814. break;
  4815. case 7:
  4816. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4817. break;
  4818. }
  4819. }
  4820. }
  4821. return destination;
  4822. };
  4823. SerializationHelper.Clone = function (creationFunction, source) {
  4824. var destination = creationFunction();
  4825. // Tags
  4826. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4827. // Properties
  4828. for (var property in destination.__serializableMembers) {
  4829. var propertyDescriptor = destination.__serializableMembers[property];
  4830. var sourceProperty = source[property];
  4831. var propertyType = propertyDescriptor.type;
  4832. if (sourceProperty !== undefined && sourceProperty !== null) {
  4833. switch (propertyType) {
  4834. case 0: // Value
  4835. case 6:
  4836. destination[property] = sourceProperty;
  4837. break;
  4838. case 1: // Texture
  4839. case 2: // Color3
  4840. case 3: // FresnelParameters
  4841. case 4: // Vector2
  4842. case 5: // Vector3
  4843. case 7:
  4844. destination[property] = sourceProperty.clone();
  4845. break;
  4846. }
  4847. }
  4848. }
  4849. return destination;
  4850. };
  4851. return SerializationHelper;
  4852. }());
  4853. BABYLON.SerializationHelper = SerializationHelper;
  4854. })(BABYLON || (BABYLON = {}));
  4855. //# sourceMappingURL=babylon.decorators.js.map
  4856. var BABYLON;
  4857. (function (BABYLON) {
  4858. /**
  4859. * A class serves as a medium between the observable and its observers
  4860. */
  4861. var EventState = (function () {
  4862. /**
  4863. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4864. */
  4865. function EventState(mask, skipNextObservers) {
  4866. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4867. this.initalize(mask, skipNextObservers);
  4868. }
  4869. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4870. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4871. this.mask = mask;
  4872. this.skipNextObservers = skipNextObservers;
  4873. return this;
  4874. };
  4875. return EventState;
  4876. }());
  4877. BABYLON.EventState = EventState;
  4878. /**
  4879. * Represent an Observer registered to a given Observable object.
  4880. */
  4881. var Observer = (function () {
  4882. function Observer(callback, mask) {
  4883. this.callback = callback;
  4884. this.mask = mask;
  4885. }
  4886. return Observer;
  4887. }());
  4888. BABYLON.Observer = Observer;
  4889. /**
  4890. * The Observable class is a simple implementation of the Observable pattern.
  4891. * 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.
  4892. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4893. * 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).
  4894. * 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.
  4895. */
  4896. var Observable = (function () {
  4897. function Observable() {
  4898. this._observers = new Array();
  4899. this._eventState = new EventState(0);
  4900. }
  4901. /**
  4902. * Create a new Observer with the specified callback
  4903. * @param callback the callback that will be executed for that Observer
  4904. * @param mask the mask used to filter observers
  4905. * @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.
  4906. */
  4907. Observable.prototype.add = function (callback, mask, insertFirst) {
  4908. if (mask === void 0) { mask = -1; }
  4909. if (insertFirst === void 0) { insertFirst = false; }
  4910. if (!callback) {
  4911. return null;
  4912. }
  4913. var observer = new Observer(callback, mask);
  4914. if (insertFirst) {
  4915. this._observers.unshift(observer);
  4916. }
  4917. else {
  4918. this._observers.push(observer);
  4919. }
  4920. return observer;
  4921. };
  4922. /**
  4923. * Remove an Observer from the Observable object
  4924. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4925. */
  4926. Observable.prototype.remove = function (observer) {
  4927. var index = this._observers.indexOf(observer);
  4928. if (index !== -1) {
  4929. this._observers.splice(index, 1);
  4930. return true;
  4931. }
  4932. return false;
  4933. };
  4934. /**
  4935. * Remove a callback from the Observable object
  4936. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4937. */
  4938. Observable.prototype.removeCallback = function (callback) {
  4939. for (var index = 0; index < this._observers.length; index++) {
  4940. if (this._observers[index].callback === callback) {
  4941. this._observers.splice(index, 1);
  4942. return true;
  4943. }
  4944. }
  4945. return false;
  4946. };
  4947. /**
  4948. * Notify all Observers by calling their respective callback with the given data
  4949. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  4950. * @param eventData
  4951. * @param mask
  4952. */
  4953. Observable.prototype.notifyObservers = function (eventData, mask) {
  4954. if (mask === void 0) { mask = -1; }
  4955. var state = this._eventState;
  4956. state.mask = mask;
  4957. state.skipNextObservers = false;
  4958. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4959. var obs = _a[_i];
  4960. if (obs.mask & mask) {
  4961. obs.callback(eventData, state);
  4962. }
  4963. if (state.skipNextObservers) {
  4964. return false;
  4965. }
  4966. }
  4967. return true;
  4968. };
  4969. /**
  4970. * return true is the Observable has at least one Observer registered
  4971. */
  4972. Observable.prototype.hasObservers = function () {
  4973. return this._observers.length > 0;
  4974. };
  4975. /**
  4976. * Clear the list of observers
  4977. */
  4978. Observable.prototype.clear = function () {
  4979. this._observers = new Array();
  4980. };
  4981. /**
  4982. * Clone the current observable
  4983. */
  4984. Observable.prototype.clone = function () {
  4985. var result = new Observable();
  4986. result._observers = this._observers.slice(0);
  4987. return result;
  4988. };
  4989. /**
  4990. * Does this observable handles observer registered with a given mask
  4991. * @param {number} trigger - the mask to be tested
  4992. * @return {boolean} whether or not one observer registered with the given mask is handeled
  4993. **/
  4994. Observable.prototype.hasSpecificMask = function (mask) {
  4995. if (mask === void 0) { mask = -1; }
  4996. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4997. var obs = _a[_i];
  4998. if (obs.mask & mask && obs.mask === mask) {
  4999. return true;
  5000. }
  5001. }
  5002. return false;
  5003. };
  5004. return Observable;
  5005. }());
  5006. BABYLON.Observable = Observable;
  5007. })(BABYLON || (BABYLON = {}));
  5008. //# sourceMappingURL=babylon.observable.js.map
  5009. var BABYLON;
  5010. (function (BABYLON) {
  5011. var Database = (function () {
  5012. function Database(urlToScene, callbackManifestChecked) {
  5013. // Handling various flavors of prefixed version of IndexedDB
  5014. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  5015. this.callbackManifestChecked = callbackManifestChecked;
  5016. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  5017. this.db = null;
  5018. this.enableSceneOffline = false;
  5019. this.enableTexturesOffline = false;
  5020. this.manifestVersionFound = 0;
  5021. this.mustUpdateRessources = false;
  5022. this.hasReachedQuota = false;
  5023. if (!Database.IDBStorageEnabled) {
  5024. this.callbackManifestChecked(true);
  5025. }
  5026. else {
  5027. this.checkManifestFile();
  5028. }
  5029. }
  5030. Database.prototype.checkManifestFile = function () {
  5031. var _this = this;
  5032. function noManifestFile() {
  5033. that.enableSceneOffline = false;
  5034. that.enableTexturesOffline = false;
  5035. that.callbackManifestChecked(false);
  5036. }
  5037. var that = this;
  5038. var timeStampUsed = false;
  5039. var manifestURL = this.currentSceneUrl + ".manifest";
  5040. var xhr = new XMLHttpRequest();
  5041. if (navigator.onLine) {
  5042. // Adding a timestamp to by-pass browsers' cache
  5043. timeStampUsed = true;
  5044. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  5045. }
  5046. xhr.open("GET", manifestURL, true);
  5047. xhr.addEventListener("load", function () {
  5048. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  5049. try {
  5050. var manifestFile = JSON.parse(xhr.response);
  5051. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  5052. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  5053. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  5054. _this.manifestVersionFound = manifestFile.version;
  5055. }
  5056. if (_this.callbackManifestChecked) {
  5057. _this.callbackManifestChecked(true);
  5058. }
  5059. }
  5060. catch (ex) {
  5061. noManifestFile();
  5062. }
  5063. }
  5064. else {
  5065. noManifestFile();
  5066. }
  5067. }, false);
  5068. xhr.addEventListener("error", function (event) {
  5069. if (timeStampUsed) {
  5070. timeStampUsed = false;
  5071. // Let's retry without the timeStamp
  5072. // It could fail when coupled with HTML5 Offline API
  5073. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  5074. xhr.open("GET", retryManifestURL, true);
  5075. xhr.send();
  5076. }
  5077. else {
  5078. noManifestFile();
  5079. }
  5080. }, false);
  5081. try {
  5082. xhr.send();
  5083. }
  5084. catch (ex) {
  5085. BABYLON.Tools.Error("Error on XHR send request.");
  5086. that.callbackManifestChecked(false);
  5087. }
  5088. };
  5089. Database.prototype.openAsync = function (successCallback, errorCallback) {
  5090. var _this = this;
  5091. function handleError() {
  5092. that.isSupported = false;
  5093. if (errorCallback)
  5094. errorCallback();
  5095. }
  5096. var that = this;
  5097. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  5098. // Your browser doesn't support IndexedDB
  5099. this.isSupported = false;
  5100. if (errorCallback)
  5101. errorCallback();
  5102. }
  5103. else {
  5104. // If the DB hasn't been opened or created yet
  5105. if (!this.db) {
  5106. this.hasReachedQuota = false;
  5107. this.isSupported = true;
  5108. var request = this.idbFactory.open("babylonjs", 1);
  5109. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  5110. request.onerror = function (event) {
  5111. handleError();
  5112. };
  5113. // executes when a version change transaction cannot complete due to other active transactions
  5114. request.onblocked = function (event) {
  5115. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  5116. handleError();
  5117. };
  5118. // DB has been opened successfully
  5119. request.onsuccess = function (event) {
  5120. _this.db = request.result;
  5121. successCallback();
  5122. };
  5123. // Initialization of the DB. Creating Scenes & Textures stores
  5124. request.onupgradeneeded = function (event) {
  5125. _this.db = (event.target).result;
  5126. try {
  5127. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  5128. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  5129. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  5130. }
  5131. catch (ex) {
  5132. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  5133. handleError();
  5134. }
  5135. };
  5136. }
  5137. else {
  5138. if (successCallback)
  5139. successCallback();
  5140. }
  5141. }
  5142. };
  5143. Database.prototype.loadImageFromDB = function (url, image) {
  5144. var _this = this;
  5145. var completeURL = Database.ReturnFullUrlLocation(url);
  5146. var saveAndLoadImage = function () {
  5147. if (!_this.hasReachedQuota && _this.db !== null) {
  5148. // the texture is not yet in the DB, let's try to save it
  5149. _this._saveImageIntoDBAsync(completeURL, image);
  5150. }
  5151. else {
  5152. image.src = url;
  5153. }
  5154. };
  5155. if (!this.mustUpdateRessources) {
  5156. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  5157. }
  5158. else {
  5159. saveAndLoadImage();
  5160. }
  5161. };
  5162. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  5163. if (this.isSupported && this.db !== null) {
  5164. var texture;
  5165. var transaction = this.db.transaction(["textures"]);
  5166. transaction.onabort = function (event) {
  5167. image.src = url;
  5168. };
  5169. transaction.oncomplete = function (event) {
  5170. var blobTextureURL;
  5171. if (texture) {
  5172. var URL = window.URL || window.webkitURL;
  5173. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  5174. image.onerror = function () {
  5175. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  5176. image.src = url;
  5177. };
  5178. image.src = blobTextureURL;
  5179. }
  5180. else {
  5181. notInDBCallback();
  5182. }
  5183. };
  5184. var getRequest = transaction.objectStore("textures").get(url);
  5185. getRequest.onsuccess = function (event) {
  5186. texture = (event.target).result;
  5187. };
  5188. getRequest.onerror = function (event) {
  5189. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  5190. image.src = url;
  5191. };
  5192. }
  5193. else {
  5194. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5195. image.src = url;
  5196. }
  5197. };
  5198. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  5199. var _this = this;
  5200. if (this.isSupported) {
  5201. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  5202. var generateBlobUrl = function () {
  5203. var blobTextureURL;
  5204. if (blob) {
  5205. var URL = window.URL || window.webkitURL;
  5206. try {
  5207. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  5208. }
  5209. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  5210. catch (ex) {
  5211. blobTextureURL = URL.createObjectURL(blob);
  5212. }
  5213. }
  5214. image.src = blobTextureURL;
  5215. };
  5216. if (Database.IsUASupportingBlobStorage) {
  5217. var xhr = new XMLHttpRequest(), blob;
  5218. xhr.open("GET", url, true);
  5219. xhr.responseType = "blob";
  5220. xhr.addEventListener("load", function () {
  5221. if (xhr.status === 200) {
  5222. // Blob as response (XHR2)
  5223. blob = xhr.response;
  5224. var transaction = _this.db.transaction(["textures"], "readwrite");
  5225. // the transaction could abort because of a QuotaExceededError error
  5226. transaction.onabort = function (event) {
  5227. try {
  5228. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5229. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5230. _this.hasReachedQuota = true;
  5231. }
  5232. }
  5233. catch (ex) { }
  5234. generateBlobUrl();
  5235. };
  5236. transaction.oncomplete = function (event) {
  5237. generateBlobUrl();
  5238. };
  5239. var newTexture = { textureUrl: url, data: blob };
  5240. try {
  5241. // Put the blob into the dabase
  5242. var addRequest = transaction.objectStore("textures").put(newTexture);
  5243. addRequest.onsuccess = function (event) {
  5244. };
  5245. addRequest.onerror = function (event) {
  5246. generateBlobUrl();
  5247. };
  5248. }
  5249. catch (ex) {
  5250. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  5251. if (ex.code === 25) {
  5252. Database.IsUASupportingBlobStorage = false;
  5253. }
  5254. image.src = url;
  5255. }
  5256. }
  5257. else {
  5258. image.src = url;
  5259. }
  5260. }, false);
  5261. xhr.addEventListener("error", function (event) {
  5262. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  5263. image.src = url;
  5264. }, false);
  5265. xhr.send();
  5266. }
  5267. else {
  5268. image.src = url;
  5269. }
  5270. }
  5271. else {
  5272. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5273. image.src = url;
  5274. }
  5275. };
  5276. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  5277. var _this = this;
  5278. var updateVersion = function (event) {
  5279. // the version is not yet in the DB or we need to update it
  5280. _this._saveVersionIntoDBAsync(url, versionLoaded);
  5281. };
  5282. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  5283. };
  5284. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  5285. var _this = this;
  5286. if (this.isSupported) {
  5287. var version;
  5288. try {
  5289. var transaction = this.db.transaction(["versions"]);
  5290. transaction.oncomplete = function (event) {
  5291. if (version) {
  5292. // If the version in the JSON file is > than the version in DB
  5293. if (_this.manifestVersionFound > version.data) {
  5294. _this.mustUpdateRessources = true;
  5295. updateInDBCallback();
  5296. }
  5297. else {
  5298. callback(version.data);
  5299. }
  5300. }
  5301. else {
  5302. _this.mustUpdateRessources = true;
  5303. updateInDBCallback();
  5304. }
  5305. };
  5306. transaction.onabort = function (event) {
  5307. callback(-1);
  5308. };
  5309. var getRequest = transaction.objectStore("versions").get(url);
  5310. getRequest.onsuccess = function (event) {
  5311. version = (event.target).result;
  5312. };
  5313. getRequest.onerror = function (event) {
  5314. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  5315. callback(-1);
  5316. };
  5317. }
  5318. catch (ex) {
  5319. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  5320. callback(-1);
  5321. }
  5322. }
  5323. else {
  5324. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5325. callback(-1);
  5326. }
  5327. };
  5328. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  5329. var _this = this;
  5330. if (this.isSupported && !this.hasReachedQuota) {
  5331. try {
  5332. // Open a transaction to the database
  5333. var transaction = this.db.transaction(["versions"], "readwrite");
  5334. // the transaction could abort because of a QuotaExceededError error
  5335. transaction.onabort = function (event) {
  5336. try {
  5337. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5338. _this.hasReachedQuota = true;
  5339. }
  5340. }
  5341. catch (ex) { }
  5342. callback(-1);
  5343. };
  5344. transaction.oncomplete = function (event) {
  5345. callback(_this.manifestVersionFound);
  5346. };
  5347. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  5348. // Put the scene into the database
  5349. var addRequest = transaction.objectStore("versions").put(newVersion);
  5350. addRequest.onsuccess = function (event) {
  5351. };
  5352. addRequest.onerror = function (event) {
  5353. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  5354. };
  5355. }
  5356. catch (ex) {
  5357. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  5358. callback(-1);
  5359. }
  5360. }
  5361. else {
  5362. callback(-1);
  5363. }
  5364. };
  5365. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  5366. var _this = this;
  5367. var completeUrl = Database.ReturnFullUrlLocation(url);
  5368. var saveAndLoadFile = function (event) {
  5369. // the scene is not yet in the DB, let's try to save it
  5370. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  5371. };
  5372. this._checkVersionFromDB(completeUrl, function (version) {
  5373. if (version !== -1) {
  5374. if (!_this.mustUpdateRessources) {
  5375. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  5376. }
  5377. else {
  5378. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  5379. }
  5380. }
  5381. else {
  5382. errorCallback();
  5383. }
  5384. });
  5385. };
  5386. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  5387. if (this.isSupported) {
  5388. var targetStore;
  5389. if (url.indexOf(".babylon") !== -1) {
  5390. targetStore = "scenes";
  5391. }
  5392. else {
  5393. targetStore = "textures";
  5394. }
  5395. var file;
  5396. var transaction = this.db.transaction([targetStore]);
  5397. transaction.oncomplete = function (event) {
  5398. if (file) {
  5399. callback(file.data);
  5400. }
  5401. else {
  5402. notInDBCallback();
  5403. }
  5404. };
  5405. transaction.onabort = function (event) {
  5406. notInDBCallback();
  5407. };
  5408. var getRequest = transaction.objectStore(targetStore).get(url);
  5409. getRequest.onsuccess = function (event) {
  5410. file = (event.target).result;
  5411. };
  5412. getRequest.onerror = function (event) {
  5413. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  5414. notInDBCallback();
  5415. };
  5416. }
  5417. else {
  5418. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5419. callback();
  5420. }
  5421. };
  5422. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  5423. var _this = this;
  5424. if (this.isSupported) {
  5425. var targetStore;
  5426. if (url.indexOf(".babylon") !== -1) {
  5427. targetStore = "scenes";
  5428. }
  5429. else {
  5430. targetStore = "textures";
  5431. }
  5432. // Create XHR
  5433. var xhr = new XMLHttpRequest(), fileData;
  5434. xhr.open("GET", url, true);
  5435. if (useArrayBuffer) {
  5436. xhr.responseType = "arraybuffer";
  5437. }
  5438. xhr.onprogress = progressCallback;
  5439. xhr.addEventListener("load", function () {
  5440. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  5441. // Blob as response (XHR2)
  5442. //fileData = xhr.responseText;
  5443. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  5444. if (!_this.hasReachedQuota) {
  5445. // Open a transaction to the database
  5446. var transaction = _this.db.transaction([targetStore], "readwrite");
  5447. // the transaction could abort because of a QuotaExceededError error
  5448. transaction.onabort = function (event) {
  5449. try {
  5450. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5451. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5452. _this.hasReachedQuota = true;
  5453. }
  5454. }
  5455. catch (ex) { }
  5456. callback(fileData);
  5457. };
  5458. transaction.oncomplete = function (event) {
  5459. callback(fileData);
  5460. };
  5461. var newFile;
  5462. if (targetStore === "scenes") {
  5463. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  5464. }
  5465. else {
  5466. newFile = { textureUrl: url, data: fileData };
  5467. }
  5468. try {
  5469. // Put the scene into the database
  5470. var addRequest = transaction.objectStore(targetStore).put(newFile);
  5471. addRequest.onsuccess = function (event) {
  5472. };
  5473. addRequest.onerror = function (event) {
  5474. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  5475. };
  5476. }
  5477. catch (ex) {
  5478. callback(fileData);
  5479. }
  5480. }
  5481. else {
  5482. callback(fileData);
  5483. }
  5484. }
  5485. else {
  5486. callback();
  5487. }
  5488. }, false);
  5489. xhr.addEventListener("error", function (event) {
  5490. BABYLON.Tools.Error("error on XHR request.");
  5491. callback();
  5492. }, false);
  5493. xhr.send();
  5494. }
  5495. else {
  5496. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5497. callback();
  5498. }
  5499. };
  5500. return Database;
  5501. }());
  5502. Database.IsUASupportingBlobStorage = true;
  5503. Database.IDBStorageEnabled = true;
  5504. Database.parseURL = function (url) {
  5505. var a = document.createElement('a');
  5506. a.href = url;
  5507. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  5508. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  5509. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  5510. return absLocation;
  5511. };
  5512. Database.ReturnFullUrlLocation = function (url) {
  5513. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  5514. return (Database.parseURL(window.location.href) + url);
  5515. }
  5516. else {
  5517. return url;
  5518. }
  5519. };
  5520. BABYLON.Database = Database;
  5521. })(BABYLON || (BABYLON = {}));
  5522. //# sourceMappingURL=babylon.database.js.map
  5523. var BABYLON;
  5524. (function (BABYLON) {
  5525. var Internals;
  5526. (function (Internals) {
  5527. /*
  5528. * Based on jsTGALoader - Javascript loader for TGA file
  5529. * By Vincent Thibault
  5530. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  5531. */
  5532. var TGATools = (function () {
  5533. function TGATools() {
  5534. }
  5535. TGATools.GetTGAHeader = function (data) {
  5536. var offset = 0;
  5537. var header = {
  5538. id_length: data[offset++],
  5539. colormap_type: data[offset++],
  5540. image_type: data[offset++],
  5541. colormap_index: data[offset++] | data[offset++] << 8,
  5542. colormap_length: data[offset++] | data[offset++] << 8,
  5543. colormap_size: data[offset++],
  5544. origin: [
  5545. data[offset++] | data[offset++] << 8,
  5546. data[offset++] | data[offset++] << 8
  5547. ],
  5548. width: data[offset++] | data[offset++] << 8,
  5549. height: data[offset++] | data[offset++] << 8,
  5550. pixel_size: data[offset++],
  5551. flags: data[offset++]
  5552. };
  5553. return header;
  5554. };
  5555. TGATools.UploadContent = function (gl, data) {
  5556. // Not enough data to contain header ?
  5557. if (data.length < 19) {
  5558. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  5559. return;
  5560. }
  5561. // Read Header
  5562. var offset = 18;
  5563. var header = TGATools.GetTGAHeader(data);
  5564. // Assume it's a valid Targa file.
  5565. if (header.id_length + offset > data.length) {
  5566. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  5567. return;
  5568. }
  5569. // Skip not needed data
  5570. offset += header.id_length;
  5571. var use_rle = false;
  5572. var use_pal = false;
  5573. var use_rgb = false;
  5574. var use_grey = false;
  5575. // Get some informations.
  5576. switch (header.image_type) {
  5577. case TGATools._TYPE_RLE_INDEXED:
  5578. use_rle = true;
  5579. case TGATools._TYPE_INDEXED:
  5580. use_pal = true;
  5581. break;
  5582. case TGATools._TYPE_RLE_RGB:
  5583. use_rle = true;
  5584. case TGATools._TYPE_RGB:
  5585. use_rgb = true;
  5586. break;
  5587. case TGATools._TYPE_RLE_GREY:
  5588. use_rle = true;
  5589. case TGATools._TYPE_GREY:
  5590. use_grey = true;
  5591. break;
  5592. }
  5593. var pixel_data;
  5594. var numAlphaBits = header.flags & 0xf;
  5595. var pixel_size = header.pixel_size >> 3;
  5596. var pixel_total = header.width * header.height * pixel_size;
  5597. // Read palettes
  5598. var palettes;
  5599. if (use_pal) {
  5600. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  5601. }
  5602. // Read LRE
  5603. if (use_rle) {
  5604. pixel_data = new Uint8Array(pixel_total);
  5605. var c, count, i;
  5606. var localOffset = 0;
  5607. var pixels = new Uint8Array(pixel_size);
  5608. while (offset < pixel_total && localOffset < pixel_total) {
  5609. c = data[offset++];
  5610. count = (c & 0x7f) + 1;
  5611. // RLE pixels
  5612. if (c & 0x80) {
  5613. // Bind pixel tmp array
  5614. for (i = 0; i < pixel_size; ++i) {
  5615. pixels[i] = data[offset++];
  5616. }
  5617. // Copy pixel array
  5618. for (i = 0; i < count; ++i) {
  5619. pixel_data.set(pixels, localOffset + i * pixel_size);
  5620. }
  5621. localOffset += pixel_size * count;
  5622. }
  5623. else {
  5624. count *= pixel_size;
  5625. for (i = 0; i < count; ++i) {
  5626. pixel_data[localOffset + i] = data[offset++];
  5627. }
  5628. localOffset += count;
  5629. }
  5630. }
  5631. }
  5632. else {
  5633. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  5634. }
  5635. // Load to texture
  5636. var x_start, y_start, x_step, y_step, y_end, x_end;
  5637. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  5638. default:
  5639. case TGATools._ORIGIN_UL:
  5640. x_start = 0;
  5641. x_step = 1;
  5642. x_end = header.width;
  5643. y_start = 0;
  5644. y_step = 1;
  5645. y_end = header.height;
  5646. break;
  5647. case TGATools._ORIGIN_BL:
  5648. x_start = 0;
  5649. x_step = 1;
  5650. x_end = header.width;
  5651. y_start = header.height - 1;
  5652. y_step = -1;
  5653. y_end = -1;
  5654. break;
  5655. case TGATools._ORIGIN_UR:
  5656. x_start = header.width - 1;
  5657. x_step = -1;
  5658. x_end = -1;
  5659. y_start = 0;
  5660. y_step = 1;
  5661. y_end = header.height;
  5662. break;
  5663. case TGATools._ORIGIN_BR:
  5664. x_start = header.width - 1;
  5665. x_step = -1;
  5666. x_end = -1;
  5667. y_start = header.height - 1;
  5668. y_step = -1;
  5669. y_end = -1;
  5670. break;
  5671. }
  5672. // Load the specify method
  5673. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  5674. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  5675. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  5676. };
  5677. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5678. var image = pixel_data, colormap = palettes;
  5679. var width = header.width, height = header.height;
  5680. var color, i = 0, x, y;
  5681. var imageData = new Uint8Array(width * height * 4);
  5682. for (y = y_start; y !== y_end; y += y_step) {
  5683. for (x = x_start; x !== x_end; x += x_step, i++) {
  5684. color = image[i];
  5685. imageData[(x + width * y) * 4 + 3] = 255;
  5686. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  5687. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  5688. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  5689. }
  5690. }
  5691. return imageData;
  5692. };
  5693. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5694. var image = pixel_data;
  5695. var width = header.width, height = header.height;
  5696. var color, i = 0, x, y;
  5697. var imageData = new Uint8Array(width * height * 4);
  5698. for (y = y_start; y !== y_end; y += y_step) {
  5699. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5700. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  5701. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  5702. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  5703. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  5704. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  5705. }
  5706. }
  5707. return imageData;
  5708. };
  5709. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5710. var image = pixel_data;
  5711. var width = header.width, height = header.height;
  5712. var i = 0, x, y;
  5713. var imageData = new Uint8Array(width * height * 4);
  5714. for (y = y_start; y !== y_end; y += y_step) {
  5715. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  5716. imageData[(x + width * y) * 4 + 3] = 255;
  5717. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5718. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5719. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5720. }
  5721. }
  5722. return imageData;
  5723. };
  5724. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5725. var image = pixel_data;
  5726. var width = header.width, height = header.height;
  5727. var i = 0, x, y;
  5728. var imageData = new Uint8Array(width * height * 4);
  5729. for (y = y_start; y !== y_end; y += y_step) {
  5730. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  5731. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5732. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5733. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5734. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  5735. }
  5736. }
  5737. return imageData;
  5738. };
  5739. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5740. var image = pixel_data;
  5741. var width = header.width, height = header.height;
  5742. var color, i = 0, x, y;
  5743. var imageData = new Uint8Array(width * height * 4);
  5744. for (y = y_start; y !== y_end; y += y_step) {
  5745. for (x = x_start; x !== x_end; x += x_step, i++) {
  5746. color = image[i];
  5747. imageData[(x + width * y) * 4 + 0] = color;
  5748. imageData[(x + width * y) * 4 + 1] = color;
  5749. imageData[(x + width * y) * 4 + 2] = color;
  5750. imageData[(x + width * y) * 4 + 3] = 255;
  5751. }
  5752. }
  5753. return imageData;
  5754. };
  5755. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5756. var image = pixel_data;
  5757. var width = header.width, height = header.height;
  5758. var i = 0, x, y;
  5759. var imageData = new Uint8Array(width * height * 4);
  5760. for (y = y_start; y !== y_end; y += y_step) {
  5761. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5762. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  5763. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  5764. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5765. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  5766. }
  5767. }
  5768. return imageData;
  5769. };
  5770. return TGATools;
  5771. }());
  5772. TGATools._TYPE_NO_DATA = 0;
  5773. TGATools._TYPE_INDEXED = 1;
  5774. TGATools._TYPE_RGB = 2;
  5775. TGATools._TYPE_GREY = 3;
  5776. TGATools._TYPE_RLE_INDEXED = 9;
  5777. TGATools._TYPE_RLE_RGB = 10;
  5778. TGATools._TYPE_RLE_GREY = 11;
  5779. TGATools._ORIGIN_MASK = 0x30;
  5780. TGATools._ORIGIN_SHIFT = 0x04;
  5781. TGATools._ORIGIN_BL = 0x00;
  5782. TGATools._ORIGIN_BR = 0x01;
  5783. TGATools._ORIGIN_UL = 0x02;
  5784. TGATools._ORIGIN_UR = 0x03;
  5785. Internals.TGATools = TGATools;
  5786. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5787. })(BABYLON || (BABYLON = {}));
  5788. //# sourceMappingURL=babylon.tools.tga.js.map
  5789. var BABYLON;
  5790. (function (BABYLON) {
  5791. var SmartArray = (function () {
  5792. function SmartArray(capacity) {
  5793. this.length = 0;
  5794. this._duplicateId = 0;
  5795. this.data = new Array(capacity);
  5796. this._id = SmartArray._GlobalId++;
  5797. }
  5798. SmartArray.prototype.push = function (value) {
  5799. this.data[this.length++] = value;
  5800. if (this.length > this.data.length) {
  5801. this.data.length *= 2;
  5802. }
  5803. if (!value.__smartArrayFlags) {
  5804. value.__smartArrayFlags = {};
  5805. }
  5806. value.__smartArrayFlags[this._id] = this._duplicateId;
  5807. };
  5808. SmartArray.prototype.forEach = function (func) {
  5809. for (var index = 0; index < this.length; index++) {
  5810. func(this.data[index]);
  5811. }
  5812. };
  5813. SmartArray.prototype.pushNoDuplicate = function (value) {
  5814. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5815. return false;
  5816. }
  5817. this.push(value);
  5818. return true;
  5819. };
  5820. SmartArray.prototype.sort = function (compareFn) {
  5821. this.data.sort(compareFn);
  5822. };
  5823. SmartArray.prototype.reset = function () {
  5824. this.length = 0;
  5825. this._duplicateId++;
  5826. };
  5827. SmartArray.prototype.dispose = function () {
  5828. this.reset();
  5829. this.data.length = 0;
  5830. };
  5831. SmartArray.prototype.concat = function (array) {
  5832. if (array.length === 0) {
  5833. return;
  5834. }
  5835. if (this.length + array.length > this.data.length) {
  5836. this.data.length = (this.length + array.length) * 2;
  5837. }
  5838. for (var index = 0; index < array.length; index++) {
  5839. this.data[this.length++] = (array.data || array)[index];
  5840. }
  5841. };
  5842. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5843. if (array.length === 0) {
  5844. return;
  5845. }
  5846. if (this.length + array.length > this.data.length) {
  5847. this.data.length = (this.length + array.length) * 2;
  5848. }
  5849. for (var index = 0; index < array.length; index++) {
  5850. var item = (array.data || array)[index];
  5851. this.pushNoDuplicate(item);
  5852. }
  5853. };
  5854. SmartArray.prototype.indexOf = function (value) {
  5855. var position = this.data.indexOf(value);
  5856. if (position >= this.length) {
  5857. return -1;
  5858. }
  5859. return position;
  5860. };
  5861. SmartArray.prototype.contains = function (value) {
  5862. return this.data.indexOf(value) !== -1;
  5863. };
  5864. return SmartArray;
  5865. }());
  5866. // Statics
  5867. SmartArray._GlobalId = 0;
  5868. BABYLON.SmartArray = SmartArray;
  5869. })(BABYLON || (BABYLON = {}));
  5870. //# sourceMappingURL=babylon.smartArray.js.map
  5871. var BABYLON;
  5872. (function (BABYLON) {
  5873. /**
  5874. * This class implement a typical dictionary using a string as key and the generic type T as value.
  5875. * The underlying implementation relies on an associative array to ensure the best performances.
  5876. * The value can be anything including 'null' but except 'undefined'
  5877. */
  5878. var StringDictionary = (function () {
  5879. function StringDictionary() {
  5880. this._count = 0;
  5881. this._data = {};
  5882. }
  5883. /**
  5884. * This will clear this dictionary and copy the content from the 'source' one.
  5885. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  5886. * @param source the dictionary to take the content from and copy to this dictionary
  5887. */
  5888. StringDictionary.prototype.copyFrom = function (source) {
  5889. var _this = this;
  5890. this.clear();
  5891. source.forEach(function (t, v) { return _this.add(t, v); });
  5892. };
  5893. /**
  5894. * Get a value based from its key
  5895. * @param key the given key to get the matching value from
  5896. * @return the value if found, otherwise undefined is returned
  5897. */
  5898. StringDictionary.prototype.get = function (key) {
  5899. var val = this._data[key];
  5900. if (val !== undefined) {
  5901. return val;
  5902. }
  5903. return undefined;
  5904. };
  5905. /**
  5906. * Get a value from its key or add it if it doesn't exist.
  5907. * This method will ensure you that a given key/data will be present in the dictionary.
  5908. * @param key the given key to get the matching value from
  5909. * @param factory the factory that will create the value if the key is not present in the dictionary.
  5910. * The factory will only be invoked if there's no data for the given key.
  5911. * @return the value corresponding to the key.
  5912. */
  5913. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  5914. var val = this.get(key);
  5915. if (val !== undefined) {
  5916. return val;
  5917. }
  5918. val = factory(key);
  5919. if (val) {
  5920. this.add(key, val);
  5921. }
  5922. return val;
  5923. };
  5924. /**
  5925. * Get a value from its key if present in the dictionary otherwise add it
  5926. * @param key the key to get the value from
  5927. * @param val if there's no such key/value pair in the dictionary add it with this value
  5928. * @return the value corresponding to the key
  5929. */
  5930. StringDictionary.prototype.getOrAdd = function (key, val) {
  5931. var curVal = this.get(key);
  5932. if (curVal !== undefined) {
  5933. return curVal;
  5934. }
  5935. this.add(key, val);
  5936. return val;
  5937. };
  5938. /**
  5939. * Check if there's a given key in the dictionary
  5940. * @param key the key to check for
  5941. * @return true if the key is present, false otherwise
  5942. */
  5943. StringDictionary.prototype.contains = function (key) {
  5944. return this._data[key] !== undefined;
  5945. };
  5946. /**
  5947. * Add a new key and its corresponding value
  5948. * @param key the key to add
  5949. * @param value the value corresponding to the key
  5950. * @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
  5951. */
  5952. StringDictionary.prototype.add = function (key, value) {
  5953. if (this._data[key] !== undefined) {
  5954. return false;
  5955. }
  5956. this._data[key] = value;
  5957. ++this._count;
  5958. return true;
  5959. };
  5960. StringDictionary.prototype.set = function (key, value) {
  5961. if (this._data[key] === undefined) {
  5962. return false;
  5963. }
  5964. this._data[key] = value;
  5965. return true;
  5966. };
  5967. /**
  5968. * Get the element of the given key and remove it from the dictionary
  5969. * @param key
  5970. */
  5971. StringDictionary.prototype.getAndRemove = function (key) {
  5972. var val = this.get(key);
  5973. if (val !== undefined) {
  5974. delete this._data[key];
  5975. --this._count;
  5976. return val;
  5977. }
  5978. return null;
  5979. };
  5980. /**
  5981. * Remove a key/value from the dictionary.
  5982. * @param key the key to remove
  5983. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  5984. */
  5985. StringDictionary.prototype.remove = function (key) {
  5986. if (this.contains(key)) {
  5987. delete this._data[key];
  5988. --this._count;
  5989. return true;
  5990. }
  5991. return false;
  5992. };
  5993. /**
  5994. * Clear the whole content of the dictionary
  5995. */
  5996. StringDictionary.prototype.clear = function () {
  5997. this._data = {};
  5998. this._count = 0;
  5999. };
  6000. Object.defineProperty(StringDictionary.prototype, "count", {
  6001. get: function () {
  6002. return this._count;
  6003. },
  6004. enumerable: true,
  6005. configurable: true
  6006. });
  6007. /**
  6008. * Execute a callback on each key/val of the dictionary.
  6009. * Note that you can remove any element in this dictionary in the callback implementation
  6010. * @param callback the callback to execute on a given key/value pair
  6011. */
  6012. StringDictionary.prototype.forEach = function (callback) {
  6013. for (var cur in this._data) {
  6014. var val = this._data[cur];
  6015. callback(cur, val);
  6016. }
  6017. };
  6018. /**
  6019. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  6020. * If the callback returns null or undefined the method will iterate to the next key/value pair
  6021. * Note that you can remove any element in this dictionary in the callback implementation
  6022. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  6023. */
  6024. StringDictionary.prototype.first = function (callback) {
  6025. for (var cur in this._data) {
  6026. var val = this._data[cur];
  6027. var res = callback(cur, val);
  6028. if (res) {
  6029. return res;
  6030. }
  6031. }
  6032. return null;
  6033. };
  6034. return StringDictionary;
  6035. }());
  6036. BABYLON.StringDictionary = StringDictionary;
  6037. })(BABYLON || (BABYLON = {}));
  6038. //# sourceMappingURL=babylon.stringDictionary.js.map
  6039. var BABYLON;
  6040. (function (BABYLON) {
  6041. // Screenshots
  6042. var screenshotCanvas;
  6043. var cloneValue = function (source, destinationObject) {
  6044. if (!source)
  6045. return null;
  6046. if (source instanceof BABYLON.Mesh) {
  6047. return null;
  6048. }
  6049. if (source instanceof BABYLON.SubMesh) {
  6050. return source.clone(destinationObject);
  6051. }
  6052. else if (source.clone) {
  6053. return source.clone();
  6054. }
  6055. return null;
  6056. };
  6057. var Tools = (function () {
  6058. function Tools() {
  6059. }
  6060. ;
  6061. Tools.Instantiate = function (className) {
  6062. var arr = className.split(".");
  6063. var fn = (window || this);
  6064. for (var i = 0, len = arr.length; i < len; i++) {
  6065. fn = fn[arr[i]];
  6066. }
  6067. if (typeof fn !== "function") {
  6068. return null;
  6069. }
  6070. return fn;
  6071. };
  6072. Tools.SetImmediate = function (action) {
  6073. if (window.setImmediate) {
  6074. window.setImmediate(action);
  6075. }
  6076. else {
  6077. setTimeout(action, 1);
  6078. }
  6079. };
  6080. Tools.IsExponentOfTwo = function (value) {
  6081. var count = 1;
  6082. do {
  6083. count *= 2;
  6084. } while (count < value);
  6085. return count === value;
  6086. };
  6087. Tools.GetExponentOfTwo = function (value, max) {
  6088. var count = 1;
  6089. do {
  6090. count *= 2;
  6091. } while (count < value);
  6092. if (count > max)
  6093. count = max;
  6094. return count;
  6095. };
  6096. Tools.GetFilename = function (path) {
  6097. var index = path.lastIndexOf("/");
  6098. if (index < 0)
  6099. return path;
  6100. return path.substring(index + 1);
  6101. };
  6102. Tools.GetDOMTextContent = function (element) {
  6103. var result = "";
  6104. var child = element.firstChild;
  6105. while (child) {
  6106. if (child.nodeType === 3) {
  6107. result += child.textContent;
  6108. }
  6109. child = child.nextSibling;
  6110. }
  6111. return result;
  6112. };
  6113. Tools.ToDegrees = function (angle) {
  6114. return angle * 180 / Math.PI;
  6115. };
  6116. Tools.ToRadians = function (angle) {
  6117. return angle * Math.PI / 180;
  6118. };
  6119. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6120. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6121. var output = "";
  6122. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6123. var i = 0;
  6124. var bytes = new Uint8Array(buffer);
  6125. while (i < bytes.length) {
  6126. chr1 = bytes[i++];
  6127. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6128. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6129. enc1 = chr1 >> 2;
  6130. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6131. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6132. enc4 = chr3 & 63;
  6133. if (isNaN(chr2)) {
  6134. enc3 = enc4 = 64;
  6135. }
  6136. else if (isNaN(chr3)) {
  6137. enc4 = 64;
  6138. }
  6139. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6140. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6141. }
  6142. return "data:image/png;base64," + output;
  6143. };
  6144. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6145. if (bias === void 0) { bias = null; }
  6146. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6147. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6148. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6149. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6150. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6151. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6152. }
  6153. if (bias) {
  6154. minimum.x -= minimum.x * bias.x + bias.y;
  6155. minimum.y -= minimum.y * bias.x + bias.y;
  6156. minimum.z -= minimum.z * bias.x + bias.y;
  6157. maximum.x += maximum.x * bias.x + bias.y;
  6158. maximum.y += maximum.y * bias.x + bias.y;
  6159. maximum.z += maximum.z * bias.x + bias.y;
  6160. }
  6161. return {
  6162. minimum: minimum,
  6163. maximum: maximum
  6164. };
  6165. };
  6166. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6167. if (bias === void 0) { bias = null; }
  6168. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6169. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6170. if (!stride) {
  6171. stride = 3;
  6172. }
  6173. for (var index = start; index < start + count; index++) {
  6174. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6175. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6176. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6177. }
  6178. if (bias) {
  6179. minimum.x -= minimum.x * bias.x + bias.y;
  6180. minimum.y -= minimum.y * bias.x + bias.y;
  6181. minimum.z -= minimum.z * bias.x + bias.y;
  6182. maximum.x += maximum.x * bias.x + bias.y;
  6183. maximum.y += maximum.y * bias.x + bias.y;
  6184. maximum.z += maximum.z * bias.x + bias.y;
  6185. }
  6186. return {
  6187. minimum: minimum,
  6188. maximum: maximum
  6189. };
  6190. };
  6191. Tools.Vector2ArrayFeeder = function (array) {
  6192. return function (index) {
  6193. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6194. var length = isFloatArray ? array.length / 2 : array.length;
  6195. if (index >= length) {
  6196. return null;
  6197. }
  6198. if (isFloatArray) {
  6199. var fa = array;
  6200. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6201. }
  6202. var a = array;
  6203. return a[index];
  6204. };
  6205. };
  6206. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6207. if (bias === void 0) { bias = null; }
  6208. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6209. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6210. var i = 0;
  6211. var cur = feeder(i++);
  6212. while (cur) {
  6213. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6214. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6215. cur = feeder(i++);
  6216. }
  6217. if (bias) {
  6218. minimum.x -= minimum.x * bias.x + bias.y;
  6219. minimum.y -= minimum.y * bias.x + bias.y;
  6220. maximum.x += maximum.x * bias.x + bias.y;
  6221. maximum.y += maximum.y * bias.x + bias.y;
  6222. }
  6223. return {
  6224. minimum: minimum,
  6225. maximum: maximum
  6226. };
  6227. };
  6228. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6229. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6230. return undefined;
  6231. return Array.isArray(obj) ? obj : [obj];
  6232. };
  6233. // Misc.
  6234. Tools.GetPointerPrefix = function () {
  6235. var eventPrefix = "pointer";
  6236. // Check if pointer events are supported
  6237. if (!window.PointerEvent && !navigator.pointerEnabled) {
  6238. eventPrefix = "mouse";
  6239. }
  6240. return eventPrefix;
  6241. };
  6242. /**
  6243. * @param func - the function to be called
  6244. * @param requester - the object that will request the next frame. Falls back to window.
  6245. */
  6246. Tools.QueueNewFrame = function (func, requester) {
  6247. if (requester === void 0) { requester = window; }
  6248. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  6249. /*if(requester.isPresenting) {
  6250. return;
  6251. } else*/ if (requester.requestAnimationFrame)
  6252. requester.requestAnimationFrame(func);
  6253. else if (requester.msRequestAnimationFrame)
  6254. requester.msRequestAnimationFrame(func);
  6255. else if (requester.webkitRequestAnimationFrame)
  6256. requester.webkitRequestAnimationFrame(func);
  6257. else if (requester.mozRequestAnimationFrame)
  6258. requester.mozRequestAnimationFrame(func);
  6259. else if (requester.oRequestAnimationFrame)
  6260. requester.oRequestAnimationFrame(func);
  6261. else {
  6262. window.setTimeout(func, 16);
  6263. }
  6264. };
  6265. Tools.RequestFullscreen = function (element) {
  6266. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6267. if (!requestFunction)
  6268. return;
  6269. requestFunction.call(element);
  6270. };
  6271. Tools.ExitFullscreen = function () {
  6272. if (document.exitFullscreen) {
  6273. document.exitFullscreen();
  6274. }
  6275. else if (document.mozCancelFullScreen) {
  6276. document.mozCancelFullScreen();
  6277. }
  6278. else if (document.webkitCancelFullScreen) {
  6279. document.webkitCancelFullScreen();
  6280. }
  6281. else if (document.msCancelFullScreen) {
  6282. document.msCancelFullScreen();
  6283. }
  6284. };
  6285. Tools.SetCorsBehavior = function (url, img) {
  6286. if (Tools.CorsBehavior) {
  6287. switch (typeof (Tools.CorsBehavior)) {
  6288. case "function":
  6289. var result = Tools.CorsBehavior(url);
  6290. if (result) {
  6291. img.crossOrigin = result;
  6292. }
  6293. break;
  6294. case "string":
  6295. default:
  6296. img.crossOrigin = Tools.CorsBehavior;
  6297. break;
  6298. }
  6299. }
  6300. };
  6301. // External files
  6302. Tools.CleanUrl = function (url) {
  6303. url = url.replace(/#/mg, "%23");
  6304. return url;
  6305. };
  6306. Tools.LoadImage = function (url, onload, onerror, database) {
  6307. if (url instanceof ArrayBuffer) {
  6308. url = Tools.EncodeArrayBufferTobase64(url);
  6309. }
  6310. url = Tools.CleanUrl(url);
  6311. var img = new Image();
  6312. if (url.substr(0, 5) !== "data:") {
  6313. Tools.SetCorsBehavior(url, img);
  6314. }
  6315. img.onload = function () {
  6316. onload(img);
  6317. };
  6318. img.onerror = function (err) {
  6319. Tools.Error("Error while trying to load image: " + url);
  6320. if (Tools.UseFallbackTexture) {
  6321. img.src = Tools.fallbackTexture;
  6322. onload(img);
  6323. }
  6324. else {
  6325. onerror();
  6326. }
  6327. };
  6328. var noIndexedDB = function () {
  6329. img.src = url;
  6330. };
  6331. var loadFromIndexedDB = function () {
  6332. database.loadImageFromDB(url, img);
  6333. };
  6334. //ANY database to do!
  6335. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6336. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6337. }
  6338. else {
  6339. if (url.indexOf("file:") === -1) {
  6340. noIndexedDB();
  6341. }
  6342. else {
  6343. var textureName = url.substring(5).toLowerCase();
  6344. if (BABYLON.FilesInput.FilesTextures[textureName]) {
  6345. try {
  6346. var blobURL;
  6347. try {
  6348. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  6349. }
  6350. catch (ex) {
  6351. // Chrome doesn't support oneTimeOnly parameter
  6352. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  6353. }
  6354. img.src = blobURL;
  6355. }
  6356. catch (e) {
  6357. img.src = null;
  6358. }
  6359. }
  6360. else {
  6361. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6362. img.src = Tools.fallbackTexture;
  6363. }
  6364. }
  6365. }
  6366. return img;
  6367. };
  6368. //ANY
  6369. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6370. url = Tools.CleanUrl(url);
  6371. var noIndexedDB = function () {
  6372. var request = new XMLHttpRequest();
  6373. var loadUrl = Tools.BaseUrl + url;
  6374. request.open('GET', loadUrl, true);
  6375. if (useArrayBuffer) {
  6376. request.responseType = "arraybuffer";
  6377. }
  6378. request.onprogress = progressCallBack;
  6379. request.onreadystatechange = function () {
  6380. if (request.readyState === 4) {
  6381. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6382. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  6383. callback(!useArrayBuffer ? request.responseText : request.response);
  6384. }
  6385. else {
  6386. if (onError) {
  6387. onError();
  6388. }
  6389. else {
  6390. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  6391. }
  6392. }
  6393. }
  6394. };
  6395. request.send(null);
  6396. };
  6397. var loadFromIndexedDB = function () {
  6398. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6399. };
  6400. if (url.indexOf("file:") !== -1) {
  6401. var fileName = url.substring(5).toLowerCase();
  6402. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6403. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6404. }
  6405. else {
  6406. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  6407. }
  6408. }
  6409. else {
  6410. // Caching all files
  6411. if (database && database.enableSceneOffline) {
  6412. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6413. }
  6414. else {
  6415. noIndexedDB();
  6416. }
  6417. }
  6418. };
  6419. /**
  6420. * Load a script (identified by an url). When the url returns, the
  6421. * content of this file is added into a new script element, attached to the DOM (body element)
  6422. */
  6423. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6424. var head = document.getElementsByTagName('head')[0];
  6425. var script = document.createElement('script');
  6426. script.type = 'text/javascript';
  6427. script.src = scriptUrl;
  6428. var self = this;
  6429. script.onload = function () {
  6430. if (onSuccess) {
  6431. onSuccess();
  6432. }
  6433. };
  6434. script.onerror = function () {
  6435. if (onError) {
  6436. onError();
  6437. }
  6438. };
  6439. head.appendChild(script);
  6440. };
  6441. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6442. var reader = new FileReader();
  6443. reader.onload = function (e) {
  6444. //target doesn't have result from ts 1.3
  6445. callback(e.target['result']);
  6446. };
  6447. reader.onprogress = progressCallback;
  6448. reader.readAsDataURL(fileToLoad);
  6449. };
  6450. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6451. var reader = new FileReader();
  6452. reader.onerror = function (e) {
  6453. Tools.Log("Error while reading file: " + fileToLoad.name);
  6454. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6455. };
  6456. reader.onload = function (e) {
  6457. //target doesn't have result from ts 1.3
  6458. callback(e.target['result']);
  6459. };
  6460. reader.onprogress = progressCallBack;
  6461. if (!useArrayBuffer) {
  6462. // Asynchronous read
  6463. reader.readAsText(fileToLoad);
  6464. }
  6465. else {
  6466. reader.readAsArrayBuffer(fileToLoad);
  6467. }
  6468. };
  6469. //returns a downloadable url to a file content.
  6470. Tools.FileAsURL = function (content) {
  6471. var fileBlob = new Blob([content]);
  6472. var url = window.URL || window.webkitURL;
  6473. var link = url.createObjectURL(fileBlob);
  6474. return link;
  6475. };
  6476. // Misc.
  6477. Tools.Format = function (value, decimals) {
  6478. if (decimals === void 0) { decimals = 2; }
  6479. return value.toFixed(decimals);
  6480. };
  6481. Tools.CheckExtends = function (v, min, max) {
  6482. if (v.x < min.x)
  6483. min.x = v.x;
  6484. if (v.y < min.y)
  6485. min.y = v.y;
  6486. if (v.z < min.z)
  6487. min.z = v.z;
  6488. if (v.x > max.x)
  6489. max.x = v.x;
  6490. if (v.y > max.y)
  6491. max.y = v.y;
  6492. if (v.z > max.z)
  6493. max.z = v.z;
  6494. };
  6495. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6496. for (var prop in source) {
  6497. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6498. continue;
  6499. }
  6500. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6501. continue;
  6502. }
  6503. var sourceValue = source[prop];
  6504. var typeOfSourceValue = typeof sourceValue;
  6505. if (typeOfSourceValue === "function") {
  6506. continue;
  6507. }
  6508. if (typeOfSourceValue === "object") {
  6509. if (sourceValue instanceof Array) {
  6510. destination[prop] = [];
  6511. if (sourceValue.length > 0) {
  6512. if (typeof sourceValue[0] == "object") {
  6513. for (var index = 0; index < sourceValue.length; index++) {
  6514. var clonedValue = cloneValue(sourceValue[index], destination);
  6515. if (destination[prop].indexOf(clonedValue) === -1) {
  6516. destination[prop].push(clonedValue);
  6517. }
  6518. }
  6519. }
  6520. else {
  6521. destination[prop] = sourceValue.slice(0);
  6522. }
  6523. }
  6524. }
  6525. else {
  6526. destination[prop] = cloneValue(sourceValue, destination);
  6527. }
  6528. }
  6529. else {
  6530. destination[prop] = sourceValue;
  6531. }
  6532. }
  6533. };
  6534. Tools.IsEmpty = function (obj) {
  6535. for (var i in obj) {
  6536. return false;
  6537. }
  6538. return true;
  6539. };
  6540. Tools.RegisterTopRootEvents = function (events) {
  6541. for (var index = 0; index < events.length; index++) {
  6542. var event = events[index];
  6543. window.addEventListener(event.name, event.handler, false);
  6544. try {
  6545. if (window.parent) {
  6546. window.parent.addEventListener(event.name, event.handler, false);
  6547. }
  6548. }
  6549. catch (e) {
  6550. // Silently fails...
  6551. }
  6552. }
  6553. };
  6554. Tools.UnregisterTopRootEvents = function (events) {
  6555. for (var index = 0; index < events.length; index++) {
  6556. var event = events[index];
  6557. window.removeEventListener(event.name, event.handler);
  6558. try {
  6559. if (window.parent) {
  6560. window.parent.removeEventListener(event.name, event.handler);
  6561. }
  6562. }
  6563. catch (e) {
  6564. // Silently fails...
  6565. }
  6566. }
  6567. };
  6568. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6569. if (mimeType === void 0) { mimeType = "image/png"; }
  6570. // Read the contents of the framebuffer
  6571. var numberOfChannelsByLine = width * 4;
  6572. var halfHeight = height / 2;
  6573. //Reading datas from WebGL
  6574. var data = engine.readPixels(0, 0, width, height);
  6575. //To flip image on Y axis.
  6576. for (var i = 0; i < halfHeight; i++) {
  6577. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6578. var currentCell = j + i * numberOfChannelsByLine;
  6579. var targetLine = height - i - 1;
  6580. var targetCell = j + targetLine * numberOfChannelsByLine;
  6581. var temp = data[currentCell];
  6582. data[currentCell] = data[targetCell];
  6583. data[targetCell] = temp;
  6584. }
  6585. }
  6586. // Create a 2D canvas to store the result
  6587. if (!screenshotCanvas) {
  6588. screenshotCanvas = document.createElement('canvas');
  6589. }
  6590. screenshotCanvas.width = width;
  6591. screenshotCanvas.height = height;
  6592. var context = screenshotCanvas.getContext('2d');
  6593. // Copy the pixels to a 2D canvas
  6594. var imageData = context.createImageData(width, height);
  6595. var castData = (imageData.data);
  6596. castData.set(data);
  6597. context.putImageData(imageData, 0, 0);
  6598. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6599. };
  6600. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6601. if (mimeType === void 0) { mimeType = "image/png"; }
  6602. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6603. if (successCallback) {
  6604. successCallback(base64Image);
  6605. }
  6606. else {
  6607. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6608. if (("download" in document.createElement("a"))) {
  6609. var a = window.document.createElement("a");
  6610. a.href = base64Image;
  6611. var date = new Date();
  6612. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6613. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6614. window.document.body.appendChild(a);
  6615. a.addEventListener("click", function () {
  6616. a.parentElement.removeChild(a);
  6617. });
  6618. a.click();
  6619. //Or opening a new tab with the image if it is not possible to automatically start download.
  6620. }
  6621. else {
  6622. var newWindow = window.open("");
  6623. var img = newWindow.document.createElement("img");
  6624. img.src = base64Image;
  6625. newWindow.document.body.appendChild(img);
  6626. }
  6627. }
  6628. };
  6629. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6630. if (mimeType === void 0) { mimeType = "image/png"; }
  6631. var width;
  6632. var height;
  6633. // If a precision value is specified
  6634. if (size.precision) {
  6635. width = Math.round(engine.getRenderWidth() * size.precision);
  6636. height = Math.round(width / engine.getAspectRatio(camera));
  6637. }
  6638. else if (size.width && size.height) {
  6639. width = size.width;
  6640. height = size.height;
  6641. }
  6642. else if (size.width && !size.height) {
  6643. width = size.width;
  6644. height = Math.round(width / engine.getAspectRatio(camera));
  6645. }
  6646. else if (size.height && !size.width) {
  6647. height = size.height;
  6648. width = Math.round(height * engine.getAspectRatio(camera));
  6649. }
  6650. else if (!isNaN(size)) {
  6651. height = size;
  6652. width = size;
  6653. }
  6654. else {
  6655. Tools.Error("Invalid 'size' parameter !");
  6656. return;
  6657. }
  6658. if (!screenshotCanvas) {
  6659. screenshotCanvas = document.createElement('canvas');
  6660. }
  6661. screenshotCanvas.width = width;
  6662. screenshotCanvas.height = height;
  6663. var renderContext = screenshotCanvas.getContext("2d");
  6664. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6665. var newWidth = width;
  6666. var newHeight = newWidth / ratio;
  6667. if (newHeight > height) {
  6668. newHeight = height;
  6669. newWidth = newHeight * ratio;
  6670. }
  6671. var offsetX = Math.max(0, width - newWidth) / 2;
  6672. var offsetY = Math.max(0, height - newHeight) / 2;
  6673. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6674. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6675. };
  6676. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6677. if (mimeType === void 0) { mimeType = "image/png"; }
  6678. if (samples === void 0) { samples = 1; }
  6679. var width;
  6680. var height;
  6681. //If a precision value is specified
  6682. if (size.precision) {
  6683. width = Math.round(engine.getRenderWidth() * size.precision);
  6684. height = Math.round(width / engine.getAspectRatio(camera));
  6685. size = { width: width, height: height };
  6686. }
  6687. else if (size.width && size.height) {
  6688. width = size.width;
  6689. height = size.height;
  6690. }
  6691. else if (size.width && !size.height) {
  6692. width = size.width;
  6693. height = Math.round(width / engine.getAspectRatio(camera));
  6694. size = { width: width, height: height };
  6695. }
  6696. else if (size.height && !size.width) {
  6697. height = size.height;
  6698. width = Math.round(height * engine.getAspectRatio(camera));
  6699. size = { width: width, height: height };
  6700. }
  6701. else if (!isNaN(size)) {
  6702. height = size;
  6703. width = size;
  6704. }
  6705. else {
  6706. Tools.Error("Invalid 'size' parameter !");
  6707. return;
  6708. }
  6709. var scene = camera.getScene();
  6710. var previousCamera = null;
  6711. if (scene.activeCamera !== camera) {
  6712. previousCamera = scene.activeCamera;
  6713. scene.activeCamera = camera;
  6714. }
  6715. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6716. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6717. texture.renderList = scene.meshes;
  6718. texture.samples = samples;
  6719. texture.onAfterRenderObservable.add(function () {
  6720. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6721. });
  6722. scene.incrementRenderId();
  6723. scene.resetCachedMaterial();
  6724. texture.render(true);
  6725. texture.dispose();
  6726. if (previousCamera) {
  6727. scene.activeCamera = previousCamera;
  6728. }
  6729. camera.getProjectionMatrix(true); // Force cache refresh;
  6730. };
  6731. // XHR response validator for local file scenario
  6732. Tools.ValidateXHRData = function (xhr, dataType) {
  6733. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6734. if (dataType === void 0) { dataType = 7; }
  6735. try {
  6736. if (dataType & 1) {
  6737. if (xhr.responseText && xhr.responseText.length > 0) {
  6738. return true;
  6739. }
  6740. else if (dataType === 1) {
  6741. return false;
  6742. }
  6743. }
  6744. if (dataType & 2) {
  6745. // Check header width and height since there is no "TGA" magic number
  6746. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6747. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6748. return true;
  6749. }
  6750. else if (dataType === 2) {
  6751. return false;
  6752. }
  6753. }
  6754. if (dataType & 4) {
  6755. // Check for the "DDS" magic number
  6756. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6757. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6758. return true;
  6759. }
  6760. else {
  6761. return false;
  6762. }
  6763. }
  6764. }
  6765. catch (e) {
  6766. // Global protection
  6767. }
  6768. return false;
  6769. };
  6770. /**
  6771. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6772. * Be aware Math.random() could cause collisions, but:
  6773. * "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"
  6774. */
  6775. Tools.RandomId = function () {
  6776. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6777. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6778. return v.toString(16);
  6779. });
  6780. };
  6781. Object.defineProperty(Tools, "NoneLogLevel", {
  6782. get: function () {
  6783. return Tools._NoneLogLevel;
  6784. },
  6785. enumerable: true,
  6786. configurable: true
  6787. });
  6788. Object.defineProperty(Tools, "MessageLogLevel", {
  6789. get: function () {
  6790. return Tools._MessageLogLevel;
  6791. },
  6792. enumerable: true,
  6793. configurable: true
  6794. });
  6795. Object.defineProperty(Tools, "WarningLogLevel", {
  6796. get: function () {
  6797. return Tools._WarningLogLevel;
  6798. },
  6799. enumerable: true,
  6800. configurable: true
  6801. });
  6802. Object.defineProperty(Tools, "ErrorLogLevel", {
  6803. get: function () {
  6804. return Tools._ErrorLogLevel;
  6805. },
  6806. enumerable: true,
  6807. configurable: true
  6808. });
  6809. Object.defineProperty(Tools, "AllLogLevel", {
  6810. get: function () {
  6811. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6812. },
  6813. enumerable: true,
  6814. configurable: true
  6815. });
  6816. Tools._AddLogEntry = function (entry) {
  6817. Tools._LogCache = entry + Tools._LogCache;
  6818. if (Tools.OnNewCacheEntry) {
  6819. Tools.OnNewCacheEntry(entry);
  6820. }
  6821. };
  6822. Tools._FormatMessage = function (message) {
  6823. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6824. var date = new Date();
  6825. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6826. };
  6827. Tools._LogDisabled = function (message) {
  6828. // nothing to do
  6829. };
  6830. Tools._LogEnabled = function (message) {
  6831. var formattedMessage = Tools._FormatMessage(message);
  6832. console.log("BJS - " + formattedMessage);
  6833. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6834. Tools._AddLogEntry(entry);
  6835. };
  6836. Tools._WarnDisabled = function (message) {
  6837. // nothing to do
  6838. };
  6839. Tools._WarnEnabled = function (message) {
  6840. var formattedMessage = Tools._FormatMessage(message);
  6841. console.warn("BJS - " + formattedMessage);
  6842. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6843. Tools._AddLogEntry(entry);
  6844. };
  6845. Tools._ErrorDisabled = function (message) {
  6846. // nothing to do
  6847. };
  6848. Tools._ErrorEnabled = function (message) {
  6849. Tools.errorsCount++;
  6850. var formattedMessage = Tools._FormatMessage(message);
  6851. console.error("BJS - " + formattedMessage);
  6852. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6853. Tools._AddLogEntry(entry);
  6854. };
  6855. Object.defineProperty(Tools, "LogCache", {
  6856. get: function () {
  6857. return Tools._LogCache;
  6858. },
  6859. enumerable: true,
  6860. configurable: true
  6861. });
  6862. Tools.ClearLogCache = function () {
  6863. Tools._LogCache = "";
  6864. Tools.errorsCount = 0;
  6865. };
  6866. Object.defineProperty(Tools, "LogLevels", {
  6867. set: function (level) {
  6868. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6869. Tools.Log = Tools._LogEnabled;
  6870. }
  6871. else {
  6872. Tools.Log = Tools._LogDisabled;
  6873. }
  6874. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6875. Tools.Warn = Tools._WarnEnabled;
  6876. }
  6877. else {
  6878. Tools.Warn = Tools._WarnDisabled;
  6879. }
  6880. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6881. Tools.Error = Tools._ErrorEnabled;
  6882. }
  6883. else {
  6884. Tools.Error = Tools._ErrorDisabled;
  6885. }
  6886. },
  6887. enumerable: true,
  6888. configurable: true
  6889. });
  6890. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6891. get: function () {
  6892. return Tools._PerformanceNoneLogLevel;
  6893. },
  6894. enumerable: true,
  6895. configurable: true
  6896. });
  6897. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6898. get: function () {
  6899. return Tools._PerformanceUserMarkLogLevel;
  6900. },
  6901. enumerable: true,
  6902. configurable: true
  6903. });
  6904. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6905. get: function () {
  6906. return Tools._PerformanceConsoleLogLevel;
  6907. },
  6908. enumerable: true,
  6909. configurable: true
  6910. });
  6911. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6912. set: function (level) {
  6913. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6914. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6915. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6916. return;
  6917. }
  6918. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6919. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6920. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6921. return;
  6922. }
  6923. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6924. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6925. },
  6926. enumerable: true,
  6927. configurable: true
  6928. });
  6929. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6930. };
  6931. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6932. };
  6933. Tools._StartUserMark = function (counterName, condition) {
  6934. if (condition === void 0) { condition = true; }
  6935. if (!condition || !Tools._performance.mark) {
  6936. return;
  6937. }
  6938. Tools._performance.mark(counterName + "-Begin");
  6939. };
  6940. Tools._EndUserMark = function (counterName, condition) {
  6941. if (condition === void 0) { condition = true; }
  6942. if (!condition || !Tools._performance.mark) {
  6943. return;
  6944. }
  6945. Tools._performance.mark(counterName + "-End");
  6946. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6947. };
  6948. Tools._StartPerformanceConsole = function (counterName, condition) {
  6949. if (condition === void 0) { condition = true; }
  6950. if (!condition) {
  6951. return;
  6952. }
  6953. Tools._StartUserMark(counterName, condition);
  6954. if (console.time) {
  6955. console.time(counterName);
  6956. }
  6957. };
  6958. Tools._EndPerformanceConsole = function (counterName, condition) {
  6959. if (condition === void 0) { condition = true; }
  6960. if (!condition) {
  6961. return;
  6962. }
  6963. Tools._EndUserMark(counterName, condition);
  6964. if (console.time) {
  6965. console.timeEnd(counterName);
  6966. }
  6967. };
  6968. Object.defineProperty(Tools, "Now", {
  6969. get: function () {
  6970. if (window.performance && window.performance.now) {
  6971. return window.performance.now();
  6972. }
  6973. return new Date().getTime();
  6974. },
  6975. enumerable: true,
  6976. configurable: true
  6977. });
  6978. /**
  6979. * This method will return the name of the class used to create the instance of the given object.
  6980. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6981. * @param object the object to get the class name from
  6982. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6983. */
  6984. Tools.getClassName = function (object, isType) {
  6985. if (isType === void 0) { isType = false; }
  6986. var name = null;
  6987. if (!isType && object.getClassName) {
  6988. name = object.getClassName();
  6989. }
  6990. else {
  6991. if (object instanceof Object) {
  6992. var classObj = isType ? object : Object.getPrototypeOf(object);
  6993. name = classObj.constructor["__bjsclassName__"];
  6994. }
  6995. if (!name) {
  6996. name = typeof object;
  6997. }
  6998. }
  6999. return name;
  7000. };
  7001. Tools.first = function (array, predicate) {
  7002. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7003. var el = array_1[_i];
  7004. if (predicate(el)) {
  7005. return el;
  7006. }
  7007. }
  7008. };
  7009. /**
  7010. * This method will return the name of the full name of the class, including its owning module (if any).
  7011. * 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).
  7012. * @param object the object to get the class name from
  7013. * @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.
  7014. */
  7015. Tools.getFullClassName = function (object, isType) {
  7016. if (isType === void 0) { isType = false; }
  7017. var className = null;
  7018. var moduleName = null;
  7019. if (!isType && object.getClassName) {
  7020. className = object.getClassName();
  7021. }
  7022. else {
  7023. if (object instanceof Object) {
  7024. var classObj = isType ? object : Object.getPrototypeOf(object);
  7025. className = classObj.constructor["__bjsclassName__"];
  7026. moduleName = classObj.constructor["__bjsmoduleName__"];
  7027. }
  7028. if (!className) {
  7029. className = typeof object;
  7030. }
  7031. }
  7032. if (!className) {
  7033. return null;
  7034. }
  7035. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7036. };
  7037. /**
  7038. * 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.
  7039. * @param array
  7040. */
  7041. Tools.arrayOrStringFeeder = function (array) {
  7042. return function (index) {
  7043. if (index >= array.length) {
  7044. return null;
  7045. }
  7046. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7047. if (val && val.getHashCode) {
  7048. val = val.getHashCode();
  7049. }
  7050. if (typeof val === "string") {
  7051. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7052. }
  7053. return val;
  7054. };
  7055. };
  7056. /**
  7057. * Compute the hashCode of a stream of number
  7058. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7059. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7060. * @return the hash code computed
  7061. */
  7062. Tools.hashCodeFromStream = function (feeder) {
  7063. // Based from here: http://stackoverflow.com/a/7616484/802124
  7064. var hash = 0;
  7065. var index = 0;
  7066. var chr = feeder(index++);
  7067. while (chr != null) {
  7068. hash = ((hash << 5) - hash) + chr;
  7069. hash |= 0; // Convert to 32bit integer
  7070. chr = feeder(index++);
  7071. }
  7072. return hash;
  7073. };
  7074. return Tools;
  7075. }());
  7076. Tools.BaseUrl = "";
  7077. Tools.CorsBehavior = "anonymous";
  7078. Tools.UseFallbackTexture = true;
  7079. // Used in case of a texture loading problem
  7080. 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";
  7081. // Logs
  7082. Tools._NoneLogLevel = 0;
  7083. Tools._MessageLogLevel = 1;
  7084. Tools._WarningLogLevel = 2;
  7085. Tools._ErrorLogLevel = 4;
  7086. Tools._LogCache = "";
  7087. Tools.errorsCount = 0;
  7088. Tools.Log = Tools._LogEnabled;
  7089. Tools.Warn = Tools._WarnEnabled;
  7090. Tools.Error = Tools._ErrorEnabled;
  7091. // Performances
  7092. Tools._PerformanceNoneLogLevel = 0;
  7093. Tools._PerformanceUserMarkLogLevel = 1;
  7094. Tools._PerformanceConsoleLogLevel = 2;
  7095. Tools._performance = window.performance;
  7096. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7097. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7098. BABYLON.Tools = Tools;
  7099. /**
  7100. * This class is used to track a performance counter which is number based.
  7101. * The user has access to many properties which give statistics of different nature
  7102. *
  7103. * The implementer can track two kinds of Performance Counter: time and count
  7104. * 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.
  7105. * 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.
  7106. */
  7107. var PerfCounter = (function () {
  7108. function PerfCounter() {
  7109. this._startMonitoringTime = 0;
  7110. this._min = 0;
  7111. this._max = 0;
  7112. this._average = 0;
  7113. this._lastSecAverage = 0;
  7114. this._current = 0;
  7115. this._totalValueCount = 0;
  7116. this._totalAccumulated = 0;
  7117. this._lastSecAccumulated = 0;
  7118. this._lastSecTime = 0;
  7119. this._lastSecValueCount = 0;
  7120. }
  7121. Object.defineProperty(PerfCounter.prototype, "min", {
  7122. /**
  7123. * Returns the smallest value ever
  7124. */
  7125. get: function () {
  7126. return this._min;
  7127. },
  7128. enumerable: true,
  7129. configurable: true
  7130. });
  7131. Object.defineProperty(PerfCounter.prototype, "max", {
  7132. /**
  7133. * Returns the biggest value ever
  7134. */
  7135. get: function () {
  7136. return this._max;
  7137. },
  7138. enumerable: true,
  7139. configurable: true
  7140. });
  7141. Object.defineProperty(PerfCounter.prototype, "average", {
  7142. /**
  7143. * Returns the average value since the performance counter is running
  7144. */
  7145. get: function () {
  7146. return this._average;
  7147. },
  7148. enumerable: true,
  7149. configurable: true
  7150. });
  7151. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7152. /**
  7153. * Returns the average value of the last second the counter was monitored
  7154. */
  7155. get: function () {
  7156. return this._lastSecAverage;
  7157. },
  7158. enumerable: true,
  7159. configurable: true
  7160. });
  7161. Object.defineProperty(PerfCounter.prototype, "current", {
  7162. /**
  7163. * Returns the current value
  7164. */
  7165. get: function () {
  7166. return this._current;
  7167. },
  7168. enumerable: true,
  7169. configurable: true
  7170. });
  7171. Object.defineProperty(PerfCounter.prototype, "total", {
  7172. get: function () {
  7173. return this._totalAccumulated;
  7174. },
  7175. enumerable: true,
  7176. configurable: true
  7177. });
  7178. /**
  7179. * Call this method to start monitoring a new frame.
  7180. * 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.
  7181. */
  7182. PerfCounter.prototype.fetchNewFrame = function () {
  7183. this._totalValueCount++;
  7184. this._current = 0;
  7185. this._lastSecValueCount++;
  7186. };
  7187. /**
  7188. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7189. * @param newCount the count value to add to the monitored count
  7190. * @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.
  7191. */
  7192. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7193. if (!PerfCounter.Enabled) {
  7194. return;
  7195. }
  7196. this._current += newCount;
  7197. if (fetchResult) {
  7198. this._fetchResult();
  7199. }
  7200. };
  7201. /**
  7202. * Start monitoring this performance counter
  7203. */
  7204. PerfCounter.prototype.beginMonitoring = function () {
  7205. if (!PerfCounter.Enabled) {
  7206. return;
  7207. }
  7208. this._startMonitoringTime = Tools.Now;
  7209. };
  7210. /**
  7211. * Compute the time lapsed since the previous beginMonitoring() call.
  7212. * @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
  7213. */
  7214. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7215. if (newFrame === void 0) { newFrame = true; }
  7216. if (!PerfCounter.Enabled) {
  7217. return;
  7218. }
  7219. if (newFrame) {
  7220. this.fetchNewFrame();
  7221. }
  7222. var currentTime = Tools.Now;
  7223. this._current = currentTime - this._startMonitoringTime;
  7224. if (newFrame) {
  7225. this._fetchResult();
  7226. }
  7227. };
  7228. PerfCounter.prototype._fetchResult = function () {
  7229. this._totalAccumulated += this._current;
  7230. this._lastSecAccumulated += this._current;
  7231. // Min/Max update
  7232. this._min = Math.min(this._min, this._current);
  7233. this._max = Math.max(this._max, this._current);
  7234. this._average = this._totalAccumulated / this._totalValueCount;
  7235. // Reset last sec?
  7236. var now = Tools.Now;
  7237. if ((now - this._lastSecTime) > 1000) {
  7238. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7239. this._lastSecTime = now;
  7240. this._lastSecAccumulated = 0;
  7241. this._lastSecValueCount = 0;
  7242. }
  7243. };
  7244. return PerfCounter;
  7245. }());
  7246. PerfCounter.Enabled = true;
  7247. BABYLON.PerfCounter = PerfCounter;
  7248. /**
  7249. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7250. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7251. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7252. * @param name The name of the class, case should be preserved
  7253. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7254. */
  7255. function className(name, module) {
  7256. return function (target) {
  7257. target["__bjsclassName__"] = name;
  7258. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7259. };
  7260. }
  7261. BABYLON.className = className;
  7262. /**
  7263. * An implementation of a loop for asynchronous functions.
  7264. */
  7265. var AsyncLoop = (function () {
  7266. /**
  7267. * Constroctor.
  7268. * @param iterations the number of iterations.
  7269. * @param _fn the function to run each iteration
  7270. * @param _successCallback the callback that will be called upon succesful execution
  7271. * @param offset starting offset.
  7272. */
  7273. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7274. if (offset === void 0) { offset = 0; }
  7275. this.iterations = iterations;
  7276. this._fn = _fn;
  7277. this._successCallback = _successCallback;
  7278. this.index = offset - 1;
  7279. this._done = false;
  7280. }
  7281. /**
  7282. * Execute the next iteration. Must be called after the last iteration was finished.
  7283. */
  7284. AsyncLoop.prototype.executeNext = function () {
  7285. if (!this._done) {
  7286. if (this.index + 1 < this.iterations) {
  7287. ++this.index;
  7288. this._fn(this);
  7289. }
  7290. else {
  7291. this.breakLoop();
  7292. }
  7293. }
  7294. };
  7295. /**
  7296. * Break the loop and run the success callback.
  7297. */
  7298. AsyncLoop.prototype.breakLoop = function () {
  7299. this._done = true;
  7300. this._successCallback();
  7301. };
  7302. /**
  7303. * Helper function
  7304. */
  7305. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7306. if (offset === void 0) { offset = 0; }
  7307. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7308. loop.executeNext();
  7309. return loop;
  7310. };
  7311. /**
  7312. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7313. * @param iterations total number of iterations
  7314. * @param syncedIterations number of synchronous iterations in each async iteration.
  7315. * @param fn the function to call each iteration.
  7316. * @param callback a success call back that will be called when iterating stops.
  7317. * @param breakFunction a break condition (optional)
  7318. * @param timeout timeout settings for the setTimeout function. default - 0.
  7319. * @constructor
  7320. */
  7321. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7322. if (timeout === void 0) { timeout = 0; }
  7323. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7324. if (breakFunction && breakFunction())
  7325. loop.breakLoop();
  7326. else {
  7327. setTimeout(function () {
  7328. for (var i = 0; i < syncedIterations; ++i) {
  7329. var iteration = (loop.index * syncedIterations) + i;
  7330. if (iteration >= iterations)
  7331. break;
  7332. fn(iteration);
  7333. if (breakFunction && breakFunction()) {
  7334. loop.breakLoop();
  7335. break;
  7336. }
  7337. }
  7338. loop.executeNext();
  7339. }, timeout);
  7340. }
  7341. }, callback);
  7342. };
  7343. return AsyncLoop;
  7344. }());
  7345. BABYLON.AsyncLoop = AsyncLoop;
  7346. })(BABYLON || (BABYLON = {}));
  7347. //# sourceMappingURL=babylon.tools.js.map
  7348. var BABYLON;
  7349. (function (BABYLON) {
  7350. var Internals;
  7351. (function (Internals) {
  7352. var _AlphaState = (function () {
  7353. /**
  7354. * Initializes the state.
  7355. */
  7356. function _AlphaState() {
  7357. this._isAlphaBlendDirty = false;
  7358. this._isBlendFunctionParametersDirty = false;
  7359. this._alphaBlend = false;
  7360. this._blendFunctionParameters = new Array(4);
  7361. this.reset();
  7362. }
  7363. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7364. get: function () {
  7365. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7366. },
  7367. enumerable: true,
  7368. configurable: true
  7369. });
  7370. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7371. get: function () {
  7372. return this._alphaBlend;
  7373. },
  7374. set: function (value) {
  7375. if (this._alphaBlend === value) {
  7376. return;
  7377. }
  7378. this._alphaBlend = value;
  7379. this._isAlphaBlendDirty = true;
  7380. },
  7381. enumerable: true,
  7382. configurable: true
  7383. });
  7384. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7385. if (this._blendFunctionParameters[0] === value0 &&
  7386. this._blendFunctionParameters[1] === value1 &&
  7387. this._blendFunctionParameters[2] === value2 &&
  7388. this._blendFunctionParameters[3] === value3) {
  7389. return;
  7390. }
  7391. this._blendFunctionParameters[0] = value0;
  7392. this._blendFunctionParameters[1] = value1;
  7393. this._blendFunctionParameters[2] = value2;
  7394. this._blendFunctionParameters[3] = value3;
  7395. this._isBlendFunctionParametersDirty = true;
  7396. };
  7397. _AlphaState.prototype.reset = function () {
  7398. this._alphaBlend = false;
  7399. this._blendFunctionParameters[0] = null;
  7400. this._blendFunctionParameters[1] = null;
  7401. this._blendFunctionParameters[2] = null;
  7402. this._blendFunctionParameters[3] = null;
  7403. this._isAlphaBlendDirty = true;
  7404. this._isBlendFunctionParametersDirty = false;
  7405. };
  7406. _AlphaState.prototype.apply = function (gl) {
  7407. if (!this.isDirty) {
  7408. return;
  7409. }
  7410. // Alpha blend
  7411. if (this._isAlphaBlendDirty) {
  7412. if (this._alphaBlend) {
  7413. gl.enable(gl.BLEND);
  7414. }
  7415. else {
  7416. gl.disable(gl.BLEND);
  7417. }
  7418. this._isAlphaBlendDirty = false;
  7419. }
  7420. // Alpha function
  7421. if (this._isBlendFunctionParametersDirty) {
  7422. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7423. this._isBlendFunctionParametersDirty = false;
  7424. }
  7425. };
  7426. return _AlphaState;
  7427. }());
  7428. Internals._AlphaState = _AlphaState;
  7429. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7430. })(BABYLON || (BABYLON = {}));
  7431. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7432. var BABYLON;
  7433. (function (BABYLON) {
  7434. var Internals;
  7435. (function (Internals) {
  7436. var _DepthCullingState = (function () {
  7437. /**
  7438. * Initializes the state.
  7439. */
  7440. function _DepthCullingState() {
  7441. this._isDepthTestDirty = false;
  7442. this._isDepthMaskDirty = false;
  7443. this._isDepthFuncDirty = false;
  7444. this._isCullFaceDirty = false;
  7445. this._isCullDirty = false;
  7446. this._isZOffsetDirty = false;
  7447. this.reset();
  7448. }
  7449. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7450. get: function () {
  7451. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7452. },
  7453. enumerable: true,
  7454. configurable: true
  7455. });
  7456. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7457. get: function () {
  7458. return this._zOffset;
  7459. },
  7460. set: function (value) {
  7461. if (this._zOffset === value) {
  7462. return;
  7463. }
  7464. this._zOffset = value;
  7465. this._isZOffsetDirty = true;
  7466. },
  7467. enumerable: true,
  7468. configurable: true
  7469. });
  7470. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7471. get: function () {
  7472. return this._cullFace;
  7473. },
  7474. set: function (value) {
  7475. if (this._cullFace === value) {
  7476. return;
  7477. }
  7478. this._cullFace = value;
  7479. this._isCullFaceDirty = true;
  7480. },
  7481. enumerable: true,
  7482. configurable: true
  7483. });
  7484. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7485. get: function () {
  7486. return this._cull;
  7487. },
  7488. set: function (value) {
  7489. if (this._cull === value) {
  7490. return;
  7491. }
  7492. this._cull = value;
  7493. this._isCullDirty = true;
  7494. },
  7495. enumerable: true,
  7496. configurable: true
  7497. });
  7498. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7499. get: function () {
  7500. return this._depthFunc;
  7501. },
  7502. set: function (value) {
  7503. if (this._depthFunc === value) {
  7504. return;
  7505. }
  7506. this._depthFunc = value;
  7507. this._isDepthFuncDirty = true;
  7508. },
  7509. enumerable: true,
  7510. configurable: true
  7511. });
  7512. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7513. get: function () {
  7514. return this._depthMask;
  7515. },
  7516. set: function (value) {
  7517. if (this._depthMask === value) {
  7518. return;
  7519. }
  7520. this._depthMask = value;
  7521. this._isDepthMaskDirty = true;
  7522. },
  7523. enumerable: true,
  7524. configurable: true
  7525. });
  7526. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7527. get: function () {
  7528. return this._depthTest;
  7529. },
  7530. set: function (value) {
  7531. if (this._depthTest === value) {
  7532. return;
  7533. }
  7534. this._depthTest = value;
  7535. this._isDepthTestDirty = true;
  7536. },
  7537. enumerable: true,
  7538. configurable: true
  7539. });
  7540. _DepthCullingState.prototype.reset = function () {
  7541. this._depthMask = true;
  7542. this._depthTest = true;
  7543. this._depthFunc = null;
  7544. this._cullFace = null;
  7545. this._cull = null;
  7546. this._zOffset = 0;
  7547. this._isDepthTestDirty = true;
  7548. this._isDepthMaskDirty = true;
  7549. this._isDepthFuncDirty = false;
  7550. this._isCullFaceDirty = false;
  7551. this._isCullDirty = false;
  7552. this._isZOffsetDirty = false;
  7553. };
  7554. _DepthCullingState.prototype.apply = function (gl) {
  7555. if (!this.isDirty) {
  7556. return;
  7557. }
  7558. // Cull
  7559. if (this._isCullDirty) {
  7560. if (this.cull) {
  7561. gl.enable(gl.CULL_FACE);
  7562. }
  7563. else {
  7564. gl.disable(gl.CULL_FACE);
  7565. }
  7566. this._isCullDirty = false;
  7567. }
  7568. // Cull face
  7569. if (this._isCullFaceDirty) {
  7570. gl.cullFace(this.cullFace);
  7571. this._isCullFaceDirty = false;
  7572. }
  7573. // Depth mask
  7574. if (this._isDepthMaskDirty) {
  7575. gl.depthMask(this.depthMask);
  7576. this._isDepthMaskDirty = false;
  7577. }
  7578. // Depth test
  7579. if (this._isDepthTestDirty) {
  7580. if (this.depthTest) {
  7581. gl.enable(gl.DEPTH_TEST);
  7582. }
  7583. else {
  7584. gl.disable(gl.DEPTH_TEST);
  7585. }
  7586. this._isDepthTestDirty = false;
  7587. }
  7588. // Depth func
  7589. if (this._isDepthFuncDirty) {
  7590. gl.depthFunc(this.depthFunc);
  7591. this._isDepthFuncDirty = false;
  7592. }
  7593. // zOffset
  7594. if (this._isZOffsetDirty) {
  7595. if (this.zOffset) {
  7596. gl.enable(gl.POLYGON_OFFSET_FILL);
  7597. gl.polygonOffset(this.zOffset, 0);
  7598. }
  7599. else {
  7600. gl.disable(gl.POLYGON_OFFSET_FILL);
  7601. }
  7602. this._isZOffsetDirty = false;
  7603. }
  7604. };
  7605. return _DepthCullingState;
  7606. }());
  7607. Internals._DepthCullingState = _DepthCullingState;
  7608. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7609. })(BABYLON || (BABYLON = {}));
  7610. //# sourceMappingURL=babylon.depthCullingState.js.map
  7611. var BABYLON;
  7612. (function (BABYLON) {
  7613. var Internals;
  7614. (function (Internals) {
  7615. var _StencilState = (function () {
  7616. function _StencilState() {
  7617. this._isStencilTestDirty = false;
  7618. this._isStencilMaskDirty = false;
  7619. this._isStencilFuncDirty = false;
  7620. this._isStencilOpDirty = false;
  7621. this.reset();
  7622. }
  7623. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7624. get: function () {
  7625. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7626. },
  7627. enumerable: true,
  7628. configurable: true
  7629. });
  7630. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7631. get: function () {
  7632. return this._stencilFunc;
  7633. },
  7634. set: function (value) {
  7635. if (this._stencilFunc === value) {
  7636. return;
  7637. }
  7638. this._stencilFunc = value;
  7639. this._isStencilFuncDirty = true;
  7640. },
  7641. enumerable: true,
  7642. configurable: true
  7643. });
  7644. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7645. get: function () {
  7646. return this._stencilFuncRef;
  7647. },
  7648. set: function (value) {
  7649. if (this._stencilFuncRef === value) {
  7650. return;
  7651. }
  7652. this._stencilFuncRef = value;
  7653. this._isStencilFuncDirty = true;
  7654. },
  7655. enumerable: true,
  7656. configurable: true
  7657. });
  7658. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7659. get: function () {
  7660. return this._stencilFuncMask;
  7661. },
  7662. set: function (value) {
  7663. if (this._stencilFuncMask === value) {
  7664. return;
  7665. }
  7666. this._stencilFuncMask = value;
  7667. this._isStencilFuncDirty = true;
  7668. },
  7669. enumerable: true,
  7670. configurable: true
  7671. });
  7672. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7673. get: function () {
  7674. return this._stencilOpStencilFail;
  7675. },
  7676. set: function (value) {
  7677. if (this._stencilOpStencilFail === value) {
  7678. return;
  7679. }
  7680. this._stencilOpStencilFail = value;
  7681. this._isStencilOpDirty = true;
  7682. },
  7683. enumerable: true,
  7684. configurable: true
  7685. });
  7686. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7687. get: function () {
  7688. return this._stencilOpDepthFail;
  7689. },
  7690. set: function (value) {
  7691. if (this._stencilOpDepthFail === value) {
  7692. return;
  7693. }
  7694. this._stencilOpDepthFail = value;
  7695. this._isStencilOpDirty = true;
  7696. },
  7697. enumerable: true,
  7698. configurable: true
  7699. });
  7700. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7701. get: function () {
  7702. return this._stencilOpStencilDepthPass;
  7703. },
  7704. set: function (value) {
  7705. if (this._stencilOpStencilDepthPass === value) {
  7706. return;
  7707. }
  7708. this._stencilOpStencilDepthPass = value;
  7709. this._isStencilOpDirty = true;
  7710. },
  7711. enumerable: true,
  7712. configurable: true
  7713. });
  7714. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7715. get: function () {
  7716. return this._stencilMask;
  7717. },
  7718. set: function (value) {
  7719. if (this._stencilMask === value) {
  7720. return;
  7721. }
  7722. this._stencilMask = value;
  7723. this._isStencilMaskDirty = true;
  7724. },
  7725. enumerable: true,
  7726. configurable: true
  7727. });
  7728. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7729. get: function () {
  7730. return this._stencilTest;
  7731. },
  7732. set: function (value) {
  7733. if (this._stencilTest === value) {
  7734. return;
  7735. }
  7736. this._stencilTest = value;
  7737. this._isStencilTestDirty = true;
  7738. },
  7739. enumerable: true,
  7740. configurable: true
  7741. });
  7742. _StencilState.prototype.reset = function () {
  7743. this._stencilTest = false;
  7744. this._stencilMask = 0xFF;
  7745. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7746. this._stencilFuncRef = 1;
  7747. this._stencilFuncMask = 0xFF;
  7748. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7749. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7750. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7751. this._isStencilTestDirty = true;
  7752. this._isStencilMaskDirty = true;
  7753. this._isStencilFuncDirty = true;
  7754. this._isStencilOpDirty = true;
  7755. };
  7756. _StencilState.prototype.apply = function (gl) {
  7757. if (!this.isDirty) {
  7758. return;
  7759. }
  7760. // Stencil test
  7761. if (this._isStencilTestDirty) {
  7762. if (this.stencilTest) {
  7763. gl.enable(gl.STENCIL_TEST);
  7764. }
  7765. else {
  7766. gl.disable(gl.STENCIL_TEST);
  7767. }
  7768. this._isStencilTestDirty = false;
  7769. }
  7770. // Stencil mask
  7771. if (this._isStencilMaskDirty) {
  7772. gl.stencilMask(this.stencilMask);
  7773. this._isStencilMaskDirty = false;
  7774. }
  7775. // Stencil func
  7776. if (this._isStencilFuncDirty) {
  7777. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7778. this._isStencilFuncDirty = false;
  7779. }
  7780. // Stencil op
  7781. if (this._isStencilOpDirty) {
  7782. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7783. this._isStencilOpDirty = false;
  7784. }
  7785. };
  7786. return _StencilState;
  7787. }());
  7788. Internals._StencilState = _StencilState;
  7789. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7790. })(BABYLON || (BABYLON = {}));
  7791. //# sourceMappingURL=babylon.stencilState.js.map
  7792. var BABYLON;
  7793. (function (BABYLON) {
  7794. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7795. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7796. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7797. gl.compileShader(shader);
  7798. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7799. throw new Error(gl.getShaderInfoLog(shader));
  7800. }
  7801. return shader;
  7802. };
  7803. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7804. var magFilter = gl.NEAREST;
  7805. var minFilter = gl.NEAREST;
  7806. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7807. magFilter = gl.LINEAR;
  7808. if (generateMipMaps) {
  7809. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7810. }
  7811. else {
  7812. minFilter = gl.LINEAR;
  7813. }
  7814. }
  7815. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7816. magFilter = gl.LINEAR;
  7817. if (generateMipMaps) {
  7818. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7819. }
  7820. else {
  7821. minFilter = gl.LINEAR;
  7822. }
  7823. }
  7824. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7825. magFilter = gl.NEAREST;
  7826. if (generateMipMaps) {
  7827. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7828. }
  7829. else {
  7830. minFilter = gl.NEAREST;
  7831. }
  7832. }
  7833. return {
  7834. min: minFilter,
  7835. mag: magFilter
  7836. };
  7837. };
  7838. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7839. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7840. var engine = scene.getEngine();
  7841. if (!engine) {
  7842. return;
  7843. }
  7844. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7845. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7846. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7847. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7848. texture._baseWidth = width;
  7849. texture._baseHeight = height;
  7850. texture._width = potWidth;
  7851. texture._height = potHeight;
  7852. texture.isReady = true;
  7853. processFunction(potWidth, potHeight);
  7854. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7855. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7856. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7857. if (!noMipmap && !isCompressed) {
  7858. gl.generateMipmap(gl.TEXTURE_2D);
  7859. }
  7860. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7861. engine.resetTextureCache();
  7862. scene._removePendingData(texture);
  7863. texture.onLoadedCallbacks.forEach(function (callback) {
  7864. callback();
  7865. });
  7866. texture.onLoadedCallbacks = [];
  7867. };
  7868. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7869. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7870. var img;
  7871. var onload = function () {
  7872. loadedImages[index] = img;
  7873. loadedImages._internalCount++;
  7874. scene._removePendingData(img);
  7875. if (loadedImages._internalCount === 6) {
  7876. onfinish(loadedImages);
  7877. }
  7878. };
  7879. var onerror = function () {
  7880. scene._removePendingData(img);
  7881. if (onErrorCallBack) {
  7882. onErrorCallBack();
  7883. }
  7884. };
  7885. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7886. scene._addPendingData(img);
  7887. };
  7888. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7889. if (onError === void 0) { onError = null; }
  7890. var loadedImages = [];
  7891. loadedImages._internalCount = 0;
  7892. for (var index = 0; index < 6; index++) {
  7893. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7894. }
  7895. };
  7896. var InstancingAttributeInfo = (function () {
  7897. function InstancingAttributeInfo() {
  7898. }
  7899. return InstancingAttributeInfo;
  7900. }());
  7901. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7902. var EngineCapabilities = (function () {
  7903. function EngineCapabilities() {
  7904. }
  7905. return EngineCapabilities;
  7906. }());
  7907. BABYLON.EngineCapabilities = EngineCapabilities;
  7908. /**
  7909. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7910. */
  7911. var Engine = (function () {
  7912. /**
  7913. * @constructor
  7914. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7915. * @param {boolean} [antialias] - enable antialias
  7916. * @param options - further options to be sent to the getContext function
  7917. */
  7918. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7919. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7920. var _this = this;
  7921. // Public members
  7922. this.isFullscreen = false;
  7923. this.isPointerLock = false;
  7924. this.cullBackFaces = true;
  7925. this.renderEvenInBackground = true;
  7926. this.preventCacheWipeBetweenFrames = false;
  7927. // To enable/disable IDB support and avoid XHR on .manifest
  7928. this.enableOfflineSupport = true;
  7929. this.scenes = new Array();
  7930. this._windowIsBackground = false;
  7931. this._webGLVersion = 1.0;
  7932. this._badOS = false;
  7933. this._drawCalls = new BABYLON.PerfCounter();
  7934. this._renderingQueueLaunched = false;
  7935. this._activeRenderLoops = [];
  7936. // FPS
  7937. this.fpsRange = 60;
  7938. this.previousFramesDuration = [];
  7939. this.fps = 60;
  7940. this.deltaTime = 0;
  7941. // States
  7942. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7943. this._stencilState = new BABYLON.Internals._StencilState();
  7944. this._alphaState = new BABYLON.Internals._AlphaState();
  7945. this._alphaMode = Engine.ALPHA_DISABLE;
  7946. // Cache
  7947. this._loadedTexturesCache = new Array();
  7948. this._maxTextureChannels = 16;
  7949. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7950. this._compiledEffects = {};
  7951. this._vertexAttribArraysEnabled = [];
  7952. this._uintIndicesCurrentlySet = false;
  7953. this._currentBoundBuffer = new Array();
  7954. this._currentBufferPointers = [];
  7955. this._currentInstanceLocations = new Array();
  7956. this._currentInstanceBuffers = new Array();
  7957. this._vaoRecordInProgress = false;
  7958. this._mustWipeVertexAttributes = false;
  7959. // Hardware supported Compressed Textures
  7960. this._texturesSupported = new Array();
  7961. this._onVRFullScreenTriggered = function () {
  7962. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7963. //get the old size before we change
  7964. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7965. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7966. //get the width and height, change the render size
  7967. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7968. var width, height;
  7969. _this.setHardwareScalingLevel(1);
  7970. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7971. }
  7972. else {
  7973. //When the specs are implemented, need to uncomment this.
  7974. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7975. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7976. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7977. _this._vrDisplayEnabled = undefined;
  7978. }
  7979. };
  7980. this._renderingCanvas = canvas;
  7981. Engine.Instances.push(this);
  7982. this._externalData = new BABYLON.StringDictionary();
  7983. options = options || {};
  7984. if (antialias != null) {
  7985. options.antialias = antialias;
  7986. }
  7987. if (options.preserveDrawingBuffer === undefined) {
  7988. options.preserveDrawingBuffer = false;
  7989. }
  7990. if (options.audioEngine === undefined) {
  7991. options.audioEngine = true;
  7992. }
  7993. if (options.stencil === undefined) {
  7994. options.stencil = true;
  7995. }
  7996. // GL
  7997. if (!options.disableWebGL2Support) {
  7998. try {
  7999. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  8000. if (this._gl) {
  8001. this._webGLVersion = 2.0;
  8002. }
  8003. }
  8004. catch (e) {
  8005. // Do nothing
  8006. }
  8007. }
  8008. if (!this._gl) {
  8009. if (!canvas) {
  8010. throw new Error("The provided canvas is null or undefined.");
  8011. }
  8012. try {
  8013. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  8014. }
  8015. catch (e) {
  8016. throw new Error("WebGL not supported");
  8017. }
  8018. }
  8019. if (!this._gl) {
  8020. throw new Error("WebGL not supported");
  8021. }
  8022. this._onBlur = function () {
  8023. _this._windowIsBackground = true;
  8024. };
  8025. this._onFocus = function () {
  8026. _this._windowIsBackground = false;
  8027. };
  8028. window.addEventListener("blur", this._onBlur);
  8029. window.addEventListener("focus", this._onFocus);
  8030. // Viewport
  8031. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8032. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8033. this.resize();
  8034. // Caps
  8035. this._isStencilEnable = options.stencil;
  8036. this._caps = new EngineCapabilities();
  8037. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8038. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8039. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8040. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8041. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8042. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8043. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8044. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8045. // Infos
  8046. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8047. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8048. if (rendererInfo != null) {
  8049. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8050. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8051. }
  8052. if (!this._glVendor) {
  8053. this._glVendor = "Unknown vendor";
  8054. }
  8055. if (!this._glRenderer) {
  8056. this._glRenderer = "Unknown renderer";
  8057. }
  8058. // Extensions
  8059. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8060. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8061. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8062. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8063. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8064. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8065. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8066. 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');
  8067. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8068. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8069. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8070. this._caps.highPrecisionShaderSupported = true;
  8071. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  8072. // Checks if some of the format renders first to allow the use of webgl inspector.
  8073. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8074. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8075. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8076. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8077. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8078. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8079. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8080. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8081. // Vertex array object
  8082. if (this._webGLVersion > 1) {
  8083. this._caps.vertexArrayObject = true;
  8084. }
  8085. else {
  8086. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8087. if (vertexArrayObjectExtension != null) {
  8088. this._caps.vertexArrayObject = true;
  8089. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8090. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8091. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8092. }
  8093. else {
  8094. this._caps.vertexArrayObject = false;
  8095. }
  8096. }
  8097. // Instances count
  8098. if (this._webGLVersion > 1) {
  8099. this._caps.instancedArrays = true;
  8100. }
  8101. else {
  8102. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8103. if (instanceExtension != null) {
  8104. this._caps.instancedArrays = true;
  8105. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8106. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8107. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8108. }
  8109. else {
  8110. this._caps.instancedArrays = false;
  8111. }
  8112. }
  8113. // Intelligently add supported compressed formats in order to check for.
  8114. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8115. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8116. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8117. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8118. if (this._caps.astc)
  8119. this.texturesSupported.push('-astc.ktx');
  8120. if (this._caps.s3tc)
  8121. this.texturesSupported.push('-dxt.ktx');
  8122. if (this._caps.pvrtc)
  8123. this.texturesSupported.push('-pvrtc.ktx');
  8124. if (this._caps.etc2)
  8125. this.texturesSupported.push('-etc2.ktx');
  8126. if (this._caps.etc1)
  8127. this.texturesSupported.push('-etc1.ktx');
  8128. if (this._gl.getShaderPrecisionFormat) {
  8129. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8130. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8131. }
  8132. // Depth buffer
  8133. this.setDepthBuffer(true);
  8134. this.setDepthFunctionToLessOrEqual();
  8135. this.setDepthWrite(true);
  8136. // Fullscreen
  8137. this._onFullscreenChange = function () {
  8138. if (document.fullscreen !== undefined) {
  8139. _this.isFullscreen = document.fullscreen;
  8140. }
  8141. else if (document.mozFullScreen !== undefined) {
  8142. _this.isFullscreen = document.mozFullScreen;
  8143. }
  8144. else if (document.webkitIsFullScreen !== undefined) {
  8145. _this.isFullscreen = document.webkitIsFullScreen;
  8146. }
  8147. else if (document.msIsFullScreen !== undefined) {
  8148. _this.isFullscreen = document.msIsFullScreen;
  8149. }
  8150. // Pointer lock
  8151. if (_this.isFullscreen && _this._pointerLockRequested) {
  8152. canvas.requestPointerLock = canvas.requestPointerLock ||
  8153. canvas.msRequestPointerLock ||
  8154. canvas.mozRequestPointerLock ||
  8155. canvas.webkitRequestPointerLock;
  8156. if (canvas.requestPointerLock) {
  8157. canvas.requestPointerLock();
  8158. }
  8159. }
  8160. };
  8161. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8162. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8163. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8164. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8165. // Pointer lock
  8166. this._onPointerLockChange = function () {
  8167. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8168. document.webkitPointerLockElement === canvas ||
  8169. document.msPointerLockElement === canvas ||
  8170. document.pointerLockElement === canvas);
  8171. };
  8172. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8173. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8174. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8175. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8176. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8177. Engine.audioEngine = new BABYLON.AudioEngine();
  8178. }
  8179. //default loading screen
  8180. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  8181. //Load WebVR Devices
  8182. if (options.autoEnableWebVR) {
  8183. this.initWebVR();
  8184. }
  8185. //Detect if we are running on a faulty buggy OS.
  8186. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  8187. //ua sniffing is the tool of the devil.
  8188. this._badOS = regexp.test(navigator.userAgent);
  8189. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8190. }
  8191. Object.defineProperty(Engine, "LastCreatedEngine", {
  8192. get: function () {
  8193. if (Engine.Instances.length === 0) {
  8194. return null;
  8195. }
  8196. return Engine.Instances[Engine.Instances.length - 1];
  8197. },
  8198. enumerable: true,
  8199. configurable: true
  8200. });
  8201. Object.defineProperty(Engine, "LastCreatedScene", {
  8202. get: function () {
  8203. var lastCreatedEngine = Engine.LastCreatedEngine;
  8204. if (!lastCreatedEngine) {
  8205. return null;
  8206. }
  8207. if (lastCreatedEngine.scenes.length === 0) {
  8208. return null;
  8209. }
  8210. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8211. },
  8212. enumerable: true,
  8213. configurable: true
  8214. });
  8215. /**
  8216. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8217. */
  8218. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8219. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8220. var engine = Engine.Instances[engineIndex];
  8221. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8222. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8223. }
  8224. }
  8225. };
  8226. Object.defineProperty(Engine, "NEVER", {
  8227. get: function () {
  8228. return Engine._NEVER;
  8229. },
  8230. enumerable: true,
  8231. configurable: true
  8232. });
  8233. Object.defineProperty(Engine, "ALWAYS", {
  8234. get: function () {
  8235. return Engine._ALWAYS;
  8236. },
  8237. enumerable: true,
  8238. configurable: true
  8239. });
  8240. Object.defineProperty(Engine, "LESS", {
  8241. get: function () {
  8242. return Engine._LESS;
  8243. },
  8244. enumerable: true,
  8245. configurable: true
  8246. });
  8247. Object.defineProperty(Engine, "EQUAL", {
  8248. get: function () {
  8249. return Engine._EQUAL;
  8250. },
  8251. enumerable: true,
  8252. configurable: true
  8253. });
  8254. Object.defineProperty(Engine, "LEQUAL", {
  8255. get: function () {
  8256. return Engine._LEQUAL;
  8257. },
  8258. enumerable: true,
  8259. configurable: true
  8260. });
  8261. Object.defineProperty(Engine, "GREATER", {
  8262. get: function () {
  8263. return Engine._GREATER;
  8264. },
  8265. enumerable: true,
  8266. configurable: true
  8267. });
  8268. Object.defineProperty(Engine, "GEQUAL", {
  8269. get: function () {
  8270. return Engine._GEQUAL;
  8271. },
  8272. enumerable: true,
  8273. configurable: true
  8274. });
  8275. Object.defineProperty(Engine, "NOTEQUAL", {
  8276. get: function () {
  8277. return Engine._NOTEQUAL;
  8278. },
  8279. enumerable: true,
  8280. configurable: true
  8281. });
  8282. Object.defineProperty(Engine, "KEEP", {
  8283. get: function () {
  8284. return Engine._KEEP;
  8285. },
  8286. enumerable: true,
  8287. configurable: true
  8288. });
  8289. Object.defineProperty(Engine, "REPLACE", {
  8290. get: function () {
  8291. return Engine._REPLACE;
  8292. },
  8293. enumerable: true,
  8294. configurable: true
  8295. });
  8296. Object.defineProperty(Engine, "INCR", {
  8297. get: function () {
  8298. return Engine._INCR;
  8299. },
  8300. enumerable: true,
  8301. configurable: true
  8302. });
  8303. Object.defineProperty(Engine, "DECR", {
  8304. get: function () {
  8305. return Engine._DECR;
  8306. },
  8307. enumerable: true,
  8308. configurable: true
  8309. });
  8310. Object.defineProperty(Engine, "INVERT", {
  8311. get: function () {
  8312. return Engine._INVERT;
  8313. },
  8314. enumerable: true,
  8315. configurable: true
  8316. });
  8317. Object.defineProperty(Engine, "INCR_WRAP", {
  8318. get: function () {
  8319. return Engine._INCR_WRAP;
  8320. },
  8321. enumerable: true,
  8322. configurable: true
  8323. });
  8324. Object.defineProperty(Engine, "DECR_WRAP", {
  8325. get: function () {
  8326. return Engine._DECR_WRAP;
  8327. },
  8328. enumerable: true,
  8329. configurable: true
  8330. });
  8331. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8332. get: function () {
  8333. return Engine._ALPHA_DISABLE;
  8334. },
  8335. enumerable: true,
  8336. configurable: true
  8337. });
  8338. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8339. get: function () {
  8340. return Engine._ALPHA_ONEONE;
  8341. },
  8342. enumerable: true,
  8343. configurable: true
  8344. });
  8345. Object.defineProperty(Engine, "ALPHA_ADD", {
  8346. get: function () {
  8347. return Engine._ALPHA_ADD;
  8348. },
  8349. enumerable: true,
  8350. configurable: true
  8351. });
  8352. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8353. get: function () {
  8354. return Engine._ALPHA_COMBINE;
  8355. },
  8356. enumerable: true,
  8357. configurable: true
  8358. });
  8359. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8360. get: function () {
  8361. return Engine._ALPHA_SUBTRACT;
  8362. },
  8363. enumerable: true,
  8364. configurable: true
  8365. });
  8366. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8367. get: function () {
  8368. return Engine._ALPHA_MULTIPLY;
  8369. },
  8370. enumerable: true,
  8371. configurable: true
  8372. });
  8373. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8374. get: function () {
  8375. return Engine._ALPHA_MAXIMIZED;
  8376. },
  8377. enumerable: true,
  8378. configurable: true
  8379. });
  8380. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8381. get: function () {
  8382. return Engine._ALPHA_PREMULTIPLIED;
  8383. },
  8384. enumerable: true,
  8385. configurable: true
  8386. });
  8387. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8388. get: function () {
  8389. return Engine._DELAYLOADSTATE_NONE;
  8390. },
  8391. enumerable: true,
  8392. configurable: true
  8393. });
  8394. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8395. get: function () {
  8396. return Engine._DELAYLOADSTATE_LOADED;
  8397. },
  8398. enumerable: true,
  8399. configurable: true
  8400. });
  8401. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8402. get: function () {
  8403. return Engine._DELAYLOADSTATE_LOADING;
  8404. },
  8405. enumerable: true,
  8406. configurable: true
  8407. });
  8408. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8409. get: function () {
  8410. return Engine._DELAYLOADSTATE_NOTLOADED;
  8411. },
  8412. enumerable: true,
  8413. configurable: true
  8414. });
  8415. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8416. get: function () {
  8417. return Engine._TEXTUREFORMAT_ALPHA;
  8418. },
  8419. enumerable: true,
  8420. configurable: true
  8421. });
  8422. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8423. get: function () {
  8424. return Engine._TEXTUREFORMAT_LUMINANCE;
  8425. },
  8426. enumerable: true,
  8427. configurable: true
  8428. });
  8429. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8430. get: function () {
  8431. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8432. },
  8433. enumerable: true,
  8434. configurable: true
  8435. });
  8436. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8437. get: function () {
  8438. return Engine._TEXTUREFORMAT_RGB;
  8439. },
  8440. enumerable: true,
  8441. configurable: true
  8442. });
  8443. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8444. get: function () {
  8445. return Engine._TEXTUREFORMAT_RGBA;
  8446. },
  8447. enumerable: true,
  8448. configurable: true
  8449. });
  8450. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8451. get: function () {
  8452. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8453. },
  8454. enumerable: true,
  8455. configurable: true
  8456. });
  8457. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8458. get: function () {
  8459. return Engine._TEXTURETYPE_FLOAT;
  8460. },
  8461. enumerable: true,
  8462. configurable: true
  8463. });
  8464. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8465. get: function () {
  8466. return Engine._TEXTURETYPE_HALF_FLOAT;
  8467. },
  8468. enumerable: true,
  8469. configurable: true
  8470. });
  8471. Object.defineProperty(Engine, "Version", {
  8472. get: function () {
  8473. return "3.0-alpha";
  8474. },
  8475. enumerable: true,
  8476. configurable: true
  8477. });
  8478. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8479. get: function () {
  8480. return this._texturesSupported;
  8481. },
  8482. enumerable: true,
  8483. configurable: true
  8484. });
  8485. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8486. get: function () {
  8487. return this._textureFormatInUse;
  8488. },
  8489. enumerable: true,
  8490. configurable: true
  8491. });
  8492. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8493. get: function () {
  8494. return this._webGLVersion;
  8495. },
  8496. enumerable: true,
  8497. configurable: true
  8498. });
  8499. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8500. /**
  8501. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8502. */
  8503. get: function () {
  8504. return this._isStencilEnable;
  8505. },
  8506. enumerable: true,
  8507. configurable: true
  8508. });
  8509. Engine.prototype._prepareWorkingCanvas = function () {
  8510. if (this._workingCanvas) {
  8511. return;
  8512. }
  8513. this._workingCanvas = document.createElement("canvas");
  8514. this._workingContext = this._workingCanvas.getContext("2d");
  8515. };
  8516. Engine.prototype.resetTextureCache = function () {
  8517. for (var index = 0; index < this._maxTextureChannels; index++) {
  8518. this._activeTexturesCache[index] = null;
  8519. }
  8520. };
  8521. Engine.prototype.getGlInfo = function () {
  8522. return {
  8523. vendor: this._glVendor,
  8524. renderer: this._glRenderer,
  8525. version: this._glVersion
  8526. };
  8527. };
  8528. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8529. if (useScreen === void 0) { useScreen = false; }
  8530. var viewport = camera.viewport;
  8531. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8532. };
  8533. Engine.prototype.getRenderWidth = function (useScreen) {
  8534. if (useScreen === void 0) { useScreen = false; }
  8535. if (!useScreen && this._currentRenderTarget) {
  8536. return this._currentRenderTarget._width;
  8537. }
  8538. return this._renderingCanvas.width;
  8539. };
  8540. Engine.prototype.getRenderHeight = function (useScreen) {
  8541. if (useScreen === void 0) { useScreen = false; }
  8542. if (!useScreen && this._currentRenderTarget) {
  8543. return this._currentRenderTarget._height;
  8544. }
  8545. return this._renderingCanvas.height;
  8546. };
  8547. Engine.prototype.getRenderingCanvas = function () {
  8548. return this._renderingCanvas;
  8549. };
  8550. Engine.prototype.getRenderingCanvasClientRect = function () {
  8551. return this._renderingCanvas.getBoundingClientRect();
  8552. };
  8553. Engine.prototype.setHardwareScalingLevel = function (level) {
  8554. this._hardwareScalingLevel = level;
  8555. this.resize();
  8556. };
  8557. Engine.prototype.getHardwareScalingLevel = function () {
  8558. return this._hardwareScalingLevel;
  8559. };
  8560. Engine.prototype.getLoadedTexturesCache = function () {
  8561. return this._loadedTexturesCache;
  8562. };
  8563. Engine.prototype.getCaps = function () {
  8564. return this._caps;
  8565. };
  8566. Object.defineProperty(Engine.prototype, "drawCalls", {
  8567. get: function () {
  8568. return this._drawCalls.current;
  8569. },
  8570. enumerable: true,
  8571. configurable: true
  8572. });
  8573. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8574. get: function () {
  8575. return this._drawCalls;
  8576. },
  8577. enumerable: true,
  8578. configurable: true
  8579. });
  8580. Engine.prototype.getDepthFunction = function () {
  8581. return this._depthCullingState.depthFunc;
  8582. };
  8583. Engine.prototype.setDepthFunction = function (depthFunc) {
  8584. this._depthCullingState.depthFunc = depthFunc;
  8585. };
  8586. Engine.prototype.setDepthFunctionToGreater = function () {
  8587. this._depthCullingState.depthFunc = this._gl.GREATER;
  8588. };
  8589. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8590. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8591. };
  8592. Engine.prototype.setDepthFunctionToLess = function () {
  8593. this._depthCullingState.depthFunc = this._gl.LESS;
  8594. };
  8595. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8596. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8597. };
  8598. Engine.prototype.getStencilBuffer = function () {
  8599. return this._stencilState.stencilTest;
  8600. };
  8601. Engine.prototype.setStencilBuffer = function (enable) {
  8602. this._stencilState.stencilTest = enable;
  8603. };
  8604. Engine.prototype.getStencilMask = function () {
  8605. return this._stencilState.stencilMask;
  8606. };
  8607. Engine.prototype.setStencilMask = function (mask) {
  8608. this._stencilState.stencilMask = mask;
  8609. };
  8610. Engine.prototype.getStencilFunction = function () {
  8611. return this._stencilState.stencilFunc;
  8612. };
  8613. Engine.prototype.getStencilFunctionReference = function () {
  8614. return this._stencilState.stencilFuncRef;
  8615. };
  8616. Engine.prototype.getStencilFunctionMask = function () {
  8617. return this._stencilState.stencilFuncMask;
  8618. };
  8619. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8620. this._stencilState.stencilFunc = stencilFunc;
  8621. };
  8622. Engine.prototype.setStencilFunctionReference = function (reference) {
  8623. this._stencilState.stencilFuncRef = reference;
  8624. };
  8625. Engine.prototype.setStencilFunctionMask = function (mask) {
  8626. this._stencilState.stencilFuncMask = mask;
  8627. };
  8628. Engine.prototype.getStencilOperationFail = function () {
  8629. return this._stencilState.stencilOpStencilFail;
  8630. };
  8631. Engine.prototype.getStencilOperationDepthFail = function () {
  8632. return this._stencilState.stencilOpDepthFail;
  8633. };
  8634. Engine.prototype.getStencilOperationPass = function () {
  8635. return this._stencilState.stencilOpStencilDepthPass;
  8636. };
  8637. Engine.prototype.setStencilOperationFail = function (operation) {
  8638. this._stencilState.stencilOpStencilFail = operation;
  8639. };
  8640. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8641. this._stencilState.stencilOpDepthFail = operation;
  8642. };
  8643. Engine.prototype.setStencilOperationPass = function (operation) {
  8644. this._stencilState.stencilOpStencilDepthPass = operation;
  8645. };
  8646. /**
  8647. * stop executing a render loop function and remove it from the execution array
  8648. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8649. */
  8650. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8651. if (!renderFunction) {
  8652. this._activeRenderLoops = [];
  8653. return;
  8654. }
  8655. var index = this._activeRenderLoops.indexOf(renderFunction);
  8656. if (index >= 0) {
  8657. this._activeRenderLoops.splice(index, 1);
  8658. }
  8659. };
  8660. Engine.prototype._renderLoop = function () {
  8661. var shouldRender = true;
  8662. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8663. shouldRender = false;
  8664. }
  8665. if (shouldRender) {
  8666. // Start new frame
  8667. this.beginFrame();
  8668. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8669. var renderFunction = this._activeRenderLoops[index];
  8670. renderFunction();
  8671. }
  8672. // Present
  8673. this.endFrame();
  8674. }
  8675. if (this._activeRenderLoops.length > 0) {
  8676. // Register new frame
  8677. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8678. }
  8679. else {
  8680. this._renderingQueueLaunched = false;
  8681. }
  8682. };
  8683. /**
  8684. * Register and execute a render loop. The engine can have more than one render function.
  8685. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8686. * @example
  8687. * engine.runRenderLoop(function () {
  8688. * scene.render()
  8689. * })
  8690. */
  8691. Engine.prototype.runRenderLoop = function (renderFunction) {
  8692. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8693. return;
  8694. }
  8695. this._activeRenderLoops.push(renderFunction);
  8696. if (!this._renderingQueueLaunched) {
  8697. this._renderingQueueLaunched = true;
  8698. this._bindedRenderFunction = this._renderLoop.bind(this);
  8699. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8700. }
  8701. };
  8702. /**
  8703. * Toggle full screen mode.
  8704. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8705. * @param {any} options - an options object to be sent to the requestFullscreen function
  8706. */
  8707. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8708. if (this.isFullscreen) {
  8709. BABYLON.Tools.ExitFullscreen();
  8710. }
  8711. else {
  8712. this._pointerLockRequested = requestPointerLock;
  8713. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8714. }
  8715. };
  8716. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8717. if (stencil === void 0) { stencil = false; }
  8718. this.applyStates();
  8719. var mode = 0;
  8720. if (backBuffer && color) {
  8721. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8722. mode |= this._gl.COLOR_BUFFER_BIT;
  8723. }
  8724. if (depth) {
  8725. this._gl.clearDepth(1.0);
  8726. mode |= this._gl.DEPTH_BUFFER_BIT;
  8727. }
  8728. if (stencil) {
  8729. this._gl.clearStencil(0);
  8730. mode |= this._gl.STENCIL_BUFFER_BIT;
  8731. }
  8732. this._gl.clear(mode);
  8733. };
  8734. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8735. var gl = this._gl;
  8736. // Save state
  8737. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8738. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8739. // Change state
  8740. gl.enable(gl.SCISSOR_TEST);
  8741. gl.scissor(x, y, width, height);
  8742. // Clear
  8743. this.clear(clearColor, true, true, true);
  8744. // Restore state
  8745. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8746. if (curScissor === true) {
  8747. gl.enable(gl.SCISSOR_TEST);
  8748. }
  8749. else {
  8750. gl.disable(gl.SCISSOR_TEST);
  8751. }
  8752. };
  8753. /**
  8754. * Set the WebGL's viewport
  8755. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8756. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8757. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8758. */
  8759. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8760. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8761. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8762. var x = viewport.x || 0;
  8763. var y = viewport.y || 0;
  8764. this._cachedViewport = viewport;
  8765. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8766. };
  8767. /**
  8768. * Directly set the WebGL Viewport
  8769. * The x, y, width & height are directly passed to the WebGL call
  8770. * @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.
  8771. */
  8772. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8773. var currentViewport = this._cachedViewport;
  8774. this._cachedViewport = null;
  8775. this._gl.viewport(x, y, width, height);
  8776. return currentViewport;
  8777. };
  8778. Engine.prototype.beginFrame = function () {
  8779. this._measureFps();
  8780. };
  8781. Engine.prototype.endFrame = function () {
  8782. //force a flush in case we are using a bad OS.
  8783. if (this._badOS) {
  8784. this.flushFramebuffer();
  8785. }
  8786. //submit frame to the vr device, if enabled
  8787. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8788. this._vrDisplayEnabled.submitFrame();
  8789. }
  8790. };
  8791. /**
  8792. * resize the view according to the canvas' size.
  8793. * @example
  8794. * window.addEventListener("resize", function () {
  8795. * engine.resize();
  8796. * });
  8797. */
  8798. Engine.prototype.resize = function () {
  8799. // We're not resizing the size of the canvas while in VR mode & presenting
  8800. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8801. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8802. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8803. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8804. }
  8805. };
  8806. /**
  8807. * force a specific size of the canvas
  8808. * @param {number} width - the new canvas' width
  8809. * @param {number} height - the new canvas' height
  8810. */
  8811. Engine.prototype.setSize = function (width, height) {
  8812. this._renderingCanvas.width = width;
  8813. this._renderingCanvas.height = height;
  8814. for (var index = 0; index < this.scenes.length; index++) {
  8815. var scene = this.scenes[index];
  8816. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8817. var cam = scene.cameras[camIndex];
  8818. cam._currentRenderId = 0;
  8819. }
  8820. }
  8821. };
  8822. //WebVR functions
  8823. Engine.prototype.initWebVR = function () {
  8824. if (!this.vrDisplaysPromise) {
  8825. this._getVRDisplays();
  8826. }
  8827. };
  8828. Engine.prototype.enableVR = function (vrDevice) {
  8829. this._vrDisplayEnabled = vrDevice;
  8830. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8831. };
  8832. Engine.prototype.disableVR = function () {
  8833. if (this._vrDisplayEnabled) {
  8834. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8835. }
  8836. };
  8837. Engine.prototype._getVRDisplays = function () {
  8838. var _this = this;
  8839. var getWebVRDevices = function (devices) {
  8840. var size = devices.length;
  8841. var i = 0;
  8842. _this._vrDisplays = devices.filter(function (device) {
  8843. return devices[i] instanceof VRDisplay;
  8844. });
  8845. return _this._vrDisplays;
  8846. };
  8847. //using a key due to typescript
  8848. if (navigator.getVRDisplays) {
  8849. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8850. }
  8851. };
  8852. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8853. this._currentRenderTarget = texture;
  8854. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8855. var gl = this._gl;
  8856. if (texture.isCube) {
  8857. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8858. }
  8859. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8860. this.wipeCaches();
  8861. };
  8862. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8863. if (this._currentFramebuffer !== framebuffer) {
  8864. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8865. this._currentFramebuffer = framebuffer;
  8866. }
  8867. };
  8868. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8869. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8870. this._currentRenderTarget = null;
  8871. // If MSAA, we need to bitblt back to main texture
  8872. var gl = this._gl;
  8873. if (texture._MSAAFramebuffer) {
  8874. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8875. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8876. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8877. }
  8878. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8879. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8880. gl.generateMipmap(gl.TEXTURE_2D);
  8881. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8882. }
  8883. if (onBeforeUnbind) {
  8884. if (texture._MSAAFramebuffer) {
  8885. // Bind the correct framebuffer
  8886. this.bindUnboundFramebuffer(texture._framebuffer);
  8887. }
  8888. onBeforeUnbind();
  8889. }
  8890. this.bindUnboundFramebuffer(null);
  8891. };
  8892. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8893. if (texture.generateMipMaps) {
  8894. var gl = this._gl;
  8895. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8896. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8897. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8898. }
  8899. };
  8900. Engine.prototype.flushFramebuffer = function () {
  8901. this._gl.flush();
  8902. };
  8903. Engine.prototype.restoreDefaultFramebuffer = function () {
  8904. this._currentRenderTarget = null;
  8905. this.bindUnboundFramebuffer(null);
  8906. this.setViewport(this._cachedViewport);
  8907. this.wipeCaches();
  8908. };
  8909. // VBOs
  8910. Engine.prototype._resetVertexBufferBinding = function () {
  8911. this.bindArrayBuffer(null);
  8912. this._cachedVertexBuffers = null;
  8913. };
  8914. Engine.prototype.createVertexBuffer = function (vertices) {
  8915. var vbo = this._gl.createBuffer();
  8916. this.bindArrayBuffer(vbo);
  8917. if (vertices instanceof Float32Array) {
  8918. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8919. }
  8920. else {
  8921. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8922. }
  8923. this._resetVertexBufferBinding();
  8924. vbo.references = 1;
  8925. return vbo;
  8926. };
  8927. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8928. var vbo = this._gl.createBuffer();
  8929. this.bindArrayBuffer(vbo);
  8930. if (vertices instanceof Float32Array) {
  8931. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8932. }
  8933. else {
  8934. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8935. }
  8936. this._resetVertexBufferBinding();
  8937. vbo.references = 1;
  8938. return vbo;
  8939. };
  8940. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8941. this.bindArrayBuffer(vertexBuffer);
  8942. if (offset === undefined) {
  8943. offset = 0;
  8944. }
  8945. if (count === undefined) {
  8946. if (vertices instanceof Float32Array) {
  8947. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8948. }
  8949. else {
  8950. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8951. }
  8952. }
  8953. else {
  8954. if (vertices instanceof Float32Array) {
  8955. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8956. }
  8957. else {
  8958. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8959. }
  8960. }
  8961. this._resetVertexBufferBinding();
  8962. };
  8963. Engine.prototype._resetIndexBufferBinding = function () {
  8964. this.bindIndexBuffer(null);
  8965. this._cachedIndexBuffer = null;
  8966. };
  8967. Engine.prototype.createIndexBuffer = function (indices) {
  8968. var vbo = this._gl.createBuffer();
  8969. this.bindIndexBuffer(vbo);
  8970. // Check for 32 bits indices
  8971. var arrayBuffer;
  8972. var need32Bits = false;
  8973. if (indices instanceof Uint16Array) {
  8974. arrayBuffer = indices;
  8975. }
  8976. else {
  8977. //check 32 bit support
  8978. if (this._caps.uintIndices) {
  8979. if (indices instanceof Uint32Array) {
  8980. arrayBuffer = indices;
  8981. need32Bits = true;
  8982. }
  8983. else {
  8984. //number[] or Int32Array, check if 32 bit is necessary
  8985. for (var index = 0; index < indices.length; index++) {
  8986. if (indices[index] > 65535) {
  8987. need32Bits = true;
  8988. break;
  8989. }
  8990. }
  8991. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8992. }
  8993. }
  8994. else {
  8995. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8996. arrayBuffer = new Uint16Array(indices);
  8997. }
  8998. }
  8999. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  9000. this._resetIndexBufferBinding();
  9001. vbo.references = 1;
  9002. vbo.is32Bits = need32Bits;
  9003. return vbo;
  9004. };
  9005. Engine.prototype.bindArrayBuffer = function (buffer) {
  9006. if (!this._vaoRecordInProgress) {
  9007. this._unBindVertexArrayObject();
  9008. }
  9009. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9010. };
  9011. Engine.prototype.bindIndexBuffer = function (buffer) {
  9012. if (!this._vaoRecordInProgress) {
  9013. this._unBindVertexArrayObject();
  9014. }
  9015. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9016. };
  9017. Engine.prototype.bindBuffer = function (buffer, target) {
  9018. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9019. this._gl.bindBuffer(target, buffer);
  9020. this._currentBoundBuffer[target] = buffer;
  9021. }
  9022. };
  9023. Engine.prototype.updateArrayBuffer = function (data) {
  9024. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9025. };
  9026. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9027. var pointer = this._currentBufferPointers[indx];
  9028. var changed = false;
  9029. if (!pointer) {
  9030. changed = true;
  9031. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  9032. }
  9033. else {
  9034. if (pointer.buffer !== buffer) {
  9035. pointer.buffer = buffer;
  9036. changed = true;
  9037. }
  9038. if (pointer.size !== size) {
  9039. pointer.size = size;
  9040. changed = true;
  9041. }
  9042. if (pointer.type !== type) {
  9043. pointer.type = type;
  9044. changed = true;
  9045. }
  9046. if (pointer.normalized !== normalized) {
  9047. pointer.normalized = normalized;
  9048. changed = true;
  9049. }
  9050. if (pointer.stride !== stride) {
  9051. pointer.stride = stride;
  9052. changed = true;
  9053. }
  9054. if (pointer.offset !== offset) {
  9055. pointer.offset = offset;
  9056. changed = true;
  9057. }
  9058. }
  9059. if (changed || this._vaoRecordInProgress) {
  9060. this.bindArrayBuffer(buffer);
  9061. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9062. }
  9063. };
  9064. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9065. if (indexBuffer == null) {
  9066. return;
  9067. }
  9068. if (this._cachedIndexBuffer !== indexBuffer) {
  9069. this._cachedIndexBuffer = indexBuffer;
  9070. this.bindIndexBuffer(indexBuffer);
  9071. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9072. }
  9073. };
  9074. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9075. var attributes = effect.getAttributesNames();
  9076. if (!this._vaoRecordInProgress) {
  9077. this._unBindVertexArrayObject();
  9078. }
  9079. this.unbindAllAttributes();
  9080. for (var index = 0; index < attributes.length; index++) {
  9081. var order = effect.getAttributeLocation(index);
  9082. if (order >= 0) {
  9083. var vertexBuffer = vertexBuffers[attributes[index]];
  9084. if (!vertexBuffer) {
  9085. continue;
  9086. }
  9087. this._gl.enableVertexAttribArray(order);
  9088. if (!this._vaoRecordInProgress) {
  9089. this._vertexAttribArraysEnabled[order] = true;
  9090. }
  9091. var buffer = vertexBuffer.getBuffer();
  9092. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9093. if (vertexBuffer.getIsInstanced()) {
  9094. this._gl.vertexAttribDivisor(order, 1);
  9095. if (!this._vaoRecordInProgress) {
  9096. this._currentInstanceLocations.push(order);
  9097. this._currentInstanceBuffers.push(buffer);
  9098. }
  9099. }
  9100. }
  9101. }
  9102. };
  9103. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9104. var vao = this._gl.createVertexArray();
  9105. this._vaoRecordInProgress = true;
  9106. this._gl.bindVertexArray(vao);
  9107. this._mustWipeVertexAttributes = true;
  9108. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9109. this.bindIndexBuffer(indexBuffer);
  9110. this._vaoRecordInProgress = false;
  9111. this._gl.bindVertexArray(null);
  9112. return vao;
  9113. };
  9114. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9115. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9116. this._cachedVertexArrayObject = vertexArrayObject;
  9117. this._gl.bindVertexArray(vertexArrayObject);
  9118. this._cachedVertexBuffers = null;
  9119. this._cachedIndexBuffer = null;
  9120. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9121. this._mustWipeVertexAttributes = true;
  9122. }
  9123. };
  9124. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9125. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9126. this._cachedVertexBuffers = vertexBuffer;
  9127. this._cachedEffectForVertexBuffers = effect;
  9128. var attributesCount = effect.getAttributesCount();
  9129. this._unBindVertexArrayObject();
  9130. this.unbindAllAttributes();
  9131. var offset = 0;
  9132. for (var index = 0; index < attributesCount; index++) {
  9133. if (index < vertexDeclaration.length) {
  9134. var order = effect.getAttributeLocation(index);
  9135. if (order >= 0) {
  9136. this._gl.enableVertexAttribArray(order);
  9137. this._vertexAttribArraysEnabled[order] = true;
  9138. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9139. }
  9140. offset += vertexDeclaration[index] * 4;
  9141. }
  9142. }
  9143. }
  9144. this._bindIndexBufferWithCache(indexBuffer);
  9145. };
  9146. Engine.prototype._unBindVertexArrayObject = function () {
  9147. if (!this._cachedVertexArrayObject) {
  9148. return;
  9149. }
  9150. this._cachedVertexArrayObject = null;
  9151. this._gl.bindVertexArray(null);
  9152. };
  9153. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9154. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9155. this._cachedVertexBuffers = vertexBuffers;
  9156. this._cachedEffectForVertexBuffers = effect;
  9157. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9158. }
  9159. this._bindIndexBufferWithCache(indexBuffer);
  9160. };
  9161. Engine.prototype.unbindInstanceAttributes = function () {
  9162. var boundBuffer;
  9163. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9164. var instancesBuffer = this._currentInstanceBuffers[i];
  9165. if (boundBuffer != instancesBuffer) {
  9166. boundBuffer = instancesBuffer;
  9167. this.bindArrayBuffer(instancesBuffer);
  9168. }
  9169. var offsetLocation = this._currentInstanceLocations[i];
  9170. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9171. }
  9172. this._currentInstanceBuffers.length = 0;
  9173. this._currentInstanceLocations.length = 0;
  9174. };
  9175. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9176. this._gl.deleteVertexArray(vao);
  9177. };
  9178. Engine.prototype._releaseBuffer = function (buffer) {
  9179. buffer.references--;
  9180. if (buffer.references === 0) {
  9181. this._gl.deleteBuffer(buffer);
  9182. return true;
  9183. }
  9184. return false;
  9185. };
  9186. Engine.prototype.createInstancesBuffer = function (capacity) {
  9187. var buffer = this._gl.createBuffer();
  9188. buffer.capacity = capacity;
  9189. this.bindArrayBuffer(buffer);
  9190. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9191. return buffer;
  9192. };
  9193. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9194. this._gl.deleteBuffer(buffer);
  9195. };
  9196. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9197. this.bindArrayBuffer(instancesBuffer);
  9198. if (data) {
  9199. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9200. }
  9201. if (offsetLocations[0].index !== undefined) {
  9202. var stride = 0;
  9203. for (var i = 0; i < offsetLocations.length; i++) {
  9204. var ai = offsetLocations[i];
  9205. stride += ai.attributeSize * 4;
  9206. }
  9207. for (var i = 0; i < offsetLocations.length; i++) {
  9208. var ai = offsetLocations[i];
  9209. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9210. this._gl.enableVertexAttribArray(ai.index);
  9211. this._vertexAttribArraysEnabled[ai.index] = true;
  9212. }
  9213. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9214. this._gl.vertexAttribDivisor(ai.index, 1);
  9215. this._currentInstanceLocations.push(ai.index);
  9216. this._currentInstanceBuffers.push(instancesBuffer);
  9217. }
  9218. }
  9219. else {
  9220. for (var index = 0; index < 4; index++) {
  9221. var offsetLocation = offsetLocations[index];
  9222. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9223. this._gl.enableVertexAttribArray(offsetLocation);
  9224. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9225. }
  9226. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9227. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9228. this._currentInstanceLocations.push(offsetLocation);
  9229. this._currentInstanceBuffers.push(instancesBuffer);
  9230. }
  9231. }
  9232. };
  9233. Engine.prototype.applyStates = function () {
  9234. this._depthCullingState.apply(this._gl);
  9235. this._stencilState.apply(this._gl);
  9236. this._alphaState.apply(this._gl);
  9237. };
  9238. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9239. // Apply states
  9240. this.applyStates();
  9241. this._drawCalls.addCount(1, false);
  9242. // Render
  9243. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9244. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9245. if (instancesCount) {
  9246. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9247. return;
  9248. }
  9249. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9250. };
  9251. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9252. // Apply states
  9253. this.applyStates();
  9254. this._drawCalls.addCount(1, false);
  9255. if (instancesCount) {
  9256. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9257. return;
  9258. }
  9259. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9260. };
  9261. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9262. // Apply states
  9263. this.applyStates();
  9264. this._drawCalls.addCount(1, false);
  9265. if (instancesCount) {
  9266. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9267. return;
  9268. }
  9269. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9270. };
  9271. // Shaders
  9272. Engine.prototype._releaseEffect = function (effect) {
  9273. if (this._compiledEffects[effect._key]) {
  9274. delete this._compiledEffects[effect._key];
  9275. if (effect.getProgram()) {
  9276. this._gl.deleteProgram(effect.getProgram());
  9277. }
  9278. }
  9279. };
  9280. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9281. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9282. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9283. var name = vertex + "+" + fragment + "@" + defines;
  9284. if (this._compiledEffects[name]) {
  9285. return this._compiledEffects[name];
  9286. }
  9287. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9288. effect._key = name;
  9289. this._compiledEffects[name] = effect;
  9290. return effect;
  9291. };
  9292. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9293. if (uniformsNames === void 0) { uniformsNames = []; }
  9294. if (samplers === void 0) { samplers = []; }
  9295. if (defines === void 0) { defines = ""; }
  9296. return this.createEffect({
  9297. vertex: "particles",
  9298. fragmentElement: fragmentName
  9299. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9300. };
  9301. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9302. context = context || this._gl;
  9303. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9304. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9305. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9306. var shaderProgram = context.createProgram();
  9307. context.attachShader(shaderProgram, vertexShader);
  9308. context.attachShader(shaderProgram, fragmentShader);
  9309. context.linkProgram(shaderProgram);
  9310. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9311. if (!linked) {
  9312. var error = context.getProgramInfoLog(shaderProgram);
  9313. if (error) {
  9314. throw new Error(error);
  9315. }
  9316. }
  9317. context.deleteShader(vertexShader);
  9318. context.deleteShader(fragmentShader);
  9319. return shaderProgram;
  9320. };
  9321. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9322. var results = [];
  9323. for (var index = 0; index < uniformsNames.length; index++) {
  9324. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9325. }
  9326. return results;
  9327. };
  9328. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9329. var results = [];
  9330. for (var index = 0; index < attributesNames.length; index++) {
  9331. try {
  9332. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9333. }
  9334. catch (e) {
  9335. results.push(-1);
  9336. }
  9337. }
  9338. return results;
  9339. };
  9340. Engine.prototype.enableEffect = function (effect) {
  9341. // Use program
  9342. this.setProgram(effect.getProgram());
  9343. this._currentEffect = effect;
  9344. if (effect.onBind) {
  9345. effect.onBind(effect);
  9346. }
  9347. };
  9348. Engine.prototype.setIntArray = function (uniform, array) {
  9349. if (!uniform)
  9350. return;
  9351. this._gl.uniform1iv(uniform, array);
  9352. };
  9353. Engine.prototype.setIntArray2 = function (uniform, array) {
  9354. if (!uniform || array.length % 2 !== 0)
  9355. return;
  9356. this._gl.uniform2iv(uniform, array);
  9357. };
  9358. Engine.prototype.setIntArray3 = function (uniform, array) {
  9359. if (!uniform || array.length % 3 !== 0)
  9360. return;
  9361. this._gl.uniform3iv(uniform, array);
  9362. };
  9363. Engine.prototype.setIntArray4 = function (uniform, array) {
  9364. if (!uniform || array.length % 4 !== 0)
  9365. return;
  9366. this._gl.uniform4iv(uniform, array);
  9367. };
  9368. Engine.prototype.setFloatArray = function (uniform, array) {
  9369. if (!uniform)
  9370. return;
  9371. this._gl.uniform1fv(uniform, array);
  9372. };
  9373. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9374. if (!uniform || array.length % 2 !== 0)
  9375. return;
  9376. this._gl.uniform2fv(uniform, array);
  9377. };
  9378. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9379. if (!uniform || array.length % 3 !== 0)
  9380. return;
  9381. this._gl.uniform3fv(uniform, array);
  9382. };
  9383. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9384. if (!uniform || array.length % 4 !== 0)
  9385. return;
  9386. this._gl.uniform4fv(uniform, array);
  9387. };
  9388. Engine.prototype.setArray = function (uniform, array) {
  9389. if (!uniform)
  9390. return;
  9391. this._gl.uniform1fv(uniform, array);
  9392. };
  9393. Engine.prototype.setArray2 = function (uniform, array) {
  9394. if (!uniform || array.length % 2 !== 0)
  9395. return;
  9396. this._gl.uniform2fv(uniform, array);
  9397. };
  9398. Engine.prototype.setArray3 = function (uniform, array) {
  9399. if (!uniform || array.length % 3 !== 0)
  9400. return;
  9401. this._gl.uniform3fv(uniform, array);
  9402. };
  9403. Engine.prototype.setArray4 = function (uniform, array) {
  9404. if (!uniform || array.length % 4 !== 0)
  9405. return;
  9406. this._gl.uniform4fv(uniform, array);
  9407. };
  9408. Engine.prototype.setMatrices = function (uniform, matrices) {
  9409. if (!uniform)
  9410. return;
  9411. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9412. };
  9413. Engine.prototype.setMatrix = function (uniform, matrix) {
  9414. if (!uniform)
  9415. return;
  9416. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9417. };
  9418. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9419. if (!uniform)
  9420. return;
  9421. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9422. };
  9423. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9424. if (!uniform)
  9425. return;
  9426. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9427. };
  9428. Engine.prototype.setFloat = function (uniform, value) {
  9429. if (!uniform)
  9430. return;
  9431. this._gl.uniform1f(uniform, value);
  9432. };
  9433. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9434. if (!uniform)
  9435. return;
  9436. this._gl.uniform2f(uniform, x, y);
  9437. };
  9438. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9439. if (!uniform)
  9440. return;
  9441. this._gl.uniform3f(uniform, x, y, z);
  9442. };
  9443. Engine.prototype.setBool = function (uniform, bool) {
  9444. if (!uniform)
  9445. return;
  9446. this._gl.uniform1i(uniform, bool);
  9447. };
  9448. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9449. if (!uniform)
  9450. return;
  9451. this._gl.uniform4f(uniform, x, y, z, w);
  9452. };
  9453. Engine.prototype.setColor3 = function (uniform, color3) {
  9454. if (!uniform)
  9455. return;
  9456. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9457. };
  9458. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9459. if (!uniform)
  9460. return;
  9461. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9462. };
  9463. // States
  9464. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9465. if (zOffset === void 0) { zOffset = 0; }
  9466. if (reverseSide === void 0) { reverseSide = false; }
  9467. // Culling
  9468. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9469. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9470. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9471. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9472. if (culling) {
  9473. this._depthCullingState.cullFace = cullFace;
  9474. this._depthCullingState.cull = true;
  9475. }
  9476. else {
  9477. this._depthCullingState.cull = false;
  9478. }
  9479. }
  9480. // Z offset
  9481. this._depthCullingState.zOffset = zOffset;
  9482. };
  9483. Engine.prototype.setDepthBuffer = function (enable) {
  9484. this._depthCullingState.depthTest = enable;
  9485. };
  9486. Engine.prototype.getDepthWrite = function () {
  9487. return this._depthCullingState.depthMask;
  9488. };
  9489. Engine.prototype.setDepthWrite = function (enable) {
  9490. this._depthCullingState.depthMask = enable;
  9491. };
  9492. Engine.prototype.setColorWrite = function (enable) {
  9493. this._gl.colorMask(enable, enable, enable, enable);
  9494. };
  9495. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9496. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9497. if (this._alphaMode === mode) {
  9498. return;
  9499. }
  9500. switch (mode) {
  9501. case Engine.ALPHA_DISABLE:
  9502. this._alphaState.alphaBlend = false;
  9503. break;
  9504. case Engine.ALPHA_PREMULTIPLIED:
  9505. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9506. this._alphaState.alphaBlend = true;
  9507. break;
  9508. case Engine.ALPHA_COMBINE:
  9509. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9510. this._alphaState.alphaBlend = true;
  9511. break;
  9512. case Engine.ALPHA_ONEONE:
  9513. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9514. this._alphaState.alphaBlend = true;
  9515. break;
  9516. case Engine.ALPHA_ADD:
  9517. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9518. this._alphaState.alphaBlend = true;
  9519. break;
  9520. case Engine.ALPHA_SUBTRACT:
  9521. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9522. this._alphaState.alphaBlend = true;
  9523. break;
  9524. case Engine.ALPHA_MULTIPLY:
  9525. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9526. this._alphaState.alphaBlend = true;
  9527. break;
  9528. case Engine.ALPHA_MAXIMIZED:
  9529. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9530. this._alphaState.alphaBlend = true;
  9531. break;
  9532. }
  9533. if (!noDepthWriteChange) {
  9534. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9535. }
  9536. this._alphaMode = mode;
  9537. };
  9538. Engine.prototype.getAlphaMode = function () {
  9539. return this._alphaMode;
  9540. };
  9541. Engine.prototype.setAlphaTesting = function (enable) {
  9542. this._alphaTest = enable;
  9543. };
  9544. Engine.prototype.getAlphaTesting = function () {
  9545. return this._alphaTest;
  9546. };
  9547. // Textures
  9548. Engine.prototype.wipeCaches = function () {
  9549. if (this.preventCacheWipeBetweenFrames) {
  9550. return;
  9551. }
  9552. this.resetTextureCache();
  9553. this._currentEffect = null;
  9554. this._stencilState.reset();
  9555. this._depthCullingState.reset();
  9556. this.setDepthFunctionToLessOrEqual();
  9557. this._alphaState.reset();
  9558. this._cachedVertexBuffers = null;
  9559. this._cachedIndexBuffer = null;
  9560. this._cachedEffectForVertexBuffers = null;
  9561. this._unBindVertexArrayObject();
  9562. this.bindIndexBuffer(null);
  9563. this.bindArrayBuffer(null);
  9564. };
  9565. /**
  9566. * Set the compressed texture format to use, based on the formats you have, and the formats
  9567. * supported by the hardware / browser.
  9568. *
  9569. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9570. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9571. * to API arguments needed to compressed textures. This puts the burden on the container
  9572. * generator to house the arcane code for determining these for current & future formats.
  9573. *
  9574. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9575. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9576. *
  9577. * Note: The result of this call is not taken into account when a texture is base64.
  9578. *
  9579. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9580. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9581. *
  9582. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9583. * @returns The extension selected.
  9584. */
  9585. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9586. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9587. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9588. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9589. return this._textureFormatInUse = this._texturesSupported[i];
  9590. }
  9591. }
  9592. }
  9593. // actively set format to nothing, to allow this to be called more than once
  9594. // and possibly fail the 2nd time
  9595. return this._textureFormatInUse = null;
  9596. };
  9597. /**
  9598. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9599. * @param {string} urlArg- This contains one of the following:
  9600. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9601. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9602. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9603. *
  9604. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9605. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9606. * @param {Scene} scene- Needed for loading to the correct scene.
  9607. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9608. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9609. * @param {callback} onError- Optional callback to be called upon failure.
  9610. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9611. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9612. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9613. *
  9614. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9615. */
  9616. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9617. var _this = this;
  9618. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9619. if (onLoad === void 0) { onLoad = null; }
  9620. if (onError === void 0) { onError = null; }
  9621. if (buffer === void 0) { buffer = null; }
  9622. var texture = fallBack ? fallBack : this._gl.createTexture();
  9623. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9624. var fromData = url.substr(0, 5) === "data:";
  9625. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9626. // establish the file extension, if possible
  9627. var lastDot = url.lastIndexOf('.');
  9628. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9629. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9630. if (isDDS) {
  9631. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9632. }
  9633. var isTGA = (extension === ".tga");
  9634. // determine if a ktx file should be substituted
  9635. var isKTX = false;
  9636. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9637. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9638. isKTX = true;
  9639. }
  9640. scene._addPendingData(texture);
  9641. texture.url = url;
  9642. texture.noMipmap = noMipmap;
  9643. texture.references = 1;
  9644. texture.samplingMode = samplingMode;
  9645. texture.onLoadedCallbacks = [];
  9646. if (onLoad) {
  9647. texture.onLoadedCallbacks.push(onLoad);
  9648. }
  9649. if (!fallBack)
  9650. this._loadedTexturesCache.push(texture);
  9651. var onerror = function () {
  9652. scene._removePendingData(texture);
  9653. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9654. if (isKTX) {
  9655. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9656. }
  9657. else if (onError) {
  9658. onError();
  9659. }
  9660. };
  9661. var callback;
  9662. // processing for non-image formats
  9663. if (isKTX || isTGA || isDDS) {
  9664. if (isKTX) {
  9665. callback = function (data) {
  9666. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9667. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9668. ktx.uploadLevels(_this._gl, !noMipmap);
  9669. }, samplingMode);
  9670. };
  9671. }
  9672. else if (isTGA) {
  9673. callback = function (arrayBuffer) {
  9674. var data = new Uint8Array(arrayBuffer);
  9675. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9676. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9677. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9678. }, samplingMode);
  9679. };
  9680. }
  9681. else if (isDDS) {
  9682. callback = function (data) {
  9683. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9684. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9685. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9686. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9687. }, samplingMode);
  9688. };
  9689. }
  9690. if (!buffer) {
  9691. BABYLON.Tools.LoadFile(url, function (data) {
  9692. callback(data);
  9693. }, null, scene.database, true, onerror);
  9694. }
  9695. else {
  9696. callback(buffer);
  9697. }
  9698. // image format processing
  9699. }
  9700. else {
  9701. var onload = function (img) {
  9702. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9703. var isPot = (img.width === potWidth && img.height === potHeight);
  9704. if (!isPot) {
  9705. _this._prepareWorkingCanvas();
  9706. _this._workingCanvas.width = potWidth;
  9707. _this._workingCanvas.height = potHeight;
  9708. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9709. _this._workingContext.imageSmoothingEnabled = false;
  9710. _this._workingContext.mozImageSmoothingEnabled = false;
  9711. _this._workingContext.oImageSmoothingEnabled = false;
  9712. _this._workingContext.webkitImageSmoothingEnabled = false;
  9713. _this._workingContext.msImageSmoothingEnabled = false;
  9714. }
  9715. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9716. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9717. _this._workingContext.imageSmoothingEnabled = true;
  9718. _this._workingContext.mozImageSmoothingEnabled = true;
  9719. _this._workingContext.oImageSmoothingEnabled = true;
  9720. _this._workingContext.webkitImageSmoothingEnabled = true;
  9721. _this._workingContext.msImageSmoothingEnabled = true;
  9722. }
  9723. }
  9724. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9725. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9726. }, samplingMode);
  9727. };
  9728. if (!fromData || isBase64)
  9729. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9730. else if (buffer instanceof Array || typeof buffer === "string")
  9731. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9732. else
  9733. onload(buffer);
  9734. }
  9735. return texture;
  9736. };
  9737. Engine.prototype._getInternalFormat = function (format) {
  9738. var internalFormat = this._gl.RGBA;
  9739. switch (format) {
  9740. case Engine.TEXTUREFORMAT_ALPHA:
  9741. internalFormat = this._gl.ALPHA;
  9742. break;
  9743. case Engine.TEXTUREFORMAT_LUMINANCE:
  9744. internalFormat = this._gl.LUMINANCE;
  9745. break;
  9746. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9747. internalFormat = this._gl.LUMINANCE_ALPHA;
  9748. break;
  9749. case Engine.TEXTUREFORMAT_RGB:
  9750. internalFormat = this._gl.RGB;
  9751. break;
  9752. case Engine.TEXTUREFORMAT_RGBA:
  9753. internalFormat = this._gl.RGBA;
  9754. break;
  9755. }
  9756. return internalFormat;
  9757. };
  9758. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9759. if (compression === void 0) { compression = null; }
  9760. var internalFormat = this._getInternalFormat(format);
  9761. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9762. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9763. if (texture._width % 4 !== 0) {
  9764. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9765. }
  9766. if (compression) {
  9767. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9768. }
  9769. else {
  9770. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9771. }
  9772. if (texture.generateMipMaps) {
  9773. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9774. }
  9775. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9776. this.resetTextureCache();
  9777. texture.isReady = true;
  9778. };
  9779. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9780. if (compression === void 0) { compression = null; }
  9781. var texture = this._gl.createTexture();
  9782. texture._baseWidth = width;
  9783. texture._baseHeight = height;
  9784. texture._width = width;
  9785. texture._height = height;
  9786. texture.references = 1;
  9787. this.updateRawTexture(texture, data, format, invertY, compression);
  9788. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9789. // Filters
  9790. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9791. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9792. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9793. if (generateMipMaps) {
  9794. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9795. }
  9796. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9797. texture.samplingMode = samplingMode;
  9798. this._loadedTexturesCache.push(texture);
  9799. return texture;
  9800. };
  9801. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9802. var texture = this._gl.createTexture();
  9803. texture._baseWidth = width;
  9804. texture._baseHeight = height;
  9805. if (generateMipMaps) {
  9806. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9807. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9808. }
  9809. this.resetTextureCache();
  9810. texture._width = width;
  9811. texture._height = height;
  9812. texture.isReady = false;
  9813. texture.generateMipMaps = generateMipMaps;
  9814. texture.references = 1;
  9815. texture.samplingMode = samplingMode;
  9816. this.updateTextureSamplingMode(samplingMode, texture);
  9817. this._loadedTexturesCache.push(texture);
  9818. return texture;
  9819. };
  9820. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9821. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9822. if (texture.isCube) {
  9823. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9824. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9825. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9826. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9827. }
  9828. else {
  9829. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9830. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9831. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9832. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9833. }
  9834. texture.samplingMode = samplingMode;
  9835. };
  9836. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9837. if (premulAlpha === void 0) { premulAlpha = false; }
  9838. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9839. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9840. if (premulAlpha) {
  9841. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9842. }
  9843. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9844. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9845. if (texture.generateMipMaps) {
  9846. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9847. }
  9848. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9849. if (premulAlpha) {
  9850. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9851. }
  9852. this.resetTextureCache();
  9853. texture.isReady = true;
  9854. };
  9855. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9856. if (texture._isDisabled) {
  9857. return;
  9858. }
  9859. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9860. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9861. try {
  9862. // Testing video texture support
  9863. if (this._videoTextureSupported === undefined) {
  9864. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9865. if (this._gl.getError() !== 0) {
  9866. this._videoTextureSupported = false;
  9867. }
  9868. else {
  9869. this._videoTextureSupported = true;
  9870. }
  9871. }
  9872. // Copy video through the current working canvas if video texture is not supported
  9873. if (!this._videoTextureSupported) {
  9874. if (!texture._workingCanvas) {
  9875. texture._workingCanvas = document.createElement("canvas");
  9876. texture._workingContext = texture._workingCanvas.getContext("2d");
  9877. texture._workingCanvas.width = texture._width;
  9878. texture._workingCanvas.height = texture._height;
  9879. }
  9880. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9881. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9882. }
  9883. else {
  9884. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9885. }
  9886. if (texture.generateMipMaps) {
  9887. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9888. }
  9889. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9890. this.resetTextureCache();
  9891. texture.isReady = true;
  9892. }
  9893. catch (ex) {
  9894. // Something unexpected
  9895. // Let's disable the texture
  9896. texture._isDisabled = true;
  9897. }
  9898. };
  9899. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9900. // old version had a "generateMipMaps" arg instead of options.
  9901. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9902. // in the same way, generateDepthBuffer is defaulted to true
  9903. var generateMipMaps = false;
  9904. var generateDepthBuffer = true;
  9905. var generateStencilBuffer = false;
  9906. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9907. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9908. if (options !== undefined) {
  9909. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9910. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9911. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9912. type = options.type === undefined ? type : options.type;
  9913. if (options.samplingMode !== undefined) {
  9914. samplingMode = options.samplingMode;
  9915. }
  9916. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9917. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9918. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9919. }
  9920. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9921. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9922. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9923. }
  9924. }
  9925. var gl = this._gl;
  9926. var texture = gl.createTexture();
  9927. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9928. var width = size.width || size;
  9929. var height = size.height || size;
  9930. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9931. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9932. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9933. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9934. }
  9935. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9936. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9937. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9938. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9939. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9940. // Create the framebuffer
  9941. var framebuffer = gl.createFramebuffer();
  9942. this.bindUnboundFramebuffer(framebuffer);
  9943. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9944. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9945. if (generateMipMaps) {
  9946. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9947. }
  9948. // Unbind
  9949. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9950. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9951. this.bindUnboundFramebuffer(null);
  9952. texture._framebuffer = framebuffer;
  9953. texture._baseWidth = width;
  9954. texture._baseHeight = height;
  9955. texture._width = width;
  9956. texture._height = height;
  9957. texture.isReady = true;
  9958. texture.samples = 1;
  9959. texture.generateMipMaps = generateMipMaps;
  9960. texture.references = 1;
  9961. texture.samplingMode = samplingMode;
  9962. texture.type = type;
  9963. texture._generateDepthBuffer = generateDepthBuffer;
  9964. texture._generateStencilBuffer = generateStencilBuffer;
  9965. this.resetTextureCache();
  9966. this._loadedTexturesCache.push(texture);
  9967. return texture;
  9968. };
  9969. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9970. if (samples === void 0) { samples = 1; }
  9971. var depthStencilBuffer = null;
  9972. var gl = this._gl;
  9973. // Create the depth/stencil buffer
  9974. if (generateStencilBuffer) {
  9975. depthStencilBuffer = gl.createRenderbuffer();
  9976. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9977. if (samples > 1) {
  9978. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9979. }
  9980. else {
  9981. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9982. }
  9983. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9984. }
  9985. else if (generateDepthBuffer) {
  9986. depthStencilBuffer = gl.createRenderbuffer();
  9987. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9988. if (samples > 1) {
  9989. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9990. }
  9991. else {
  9992. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9993. }
  9994. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9995. }
  9996. return depthStencilBuffer;
  9997. };
  9998. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9999. if (this.webGLVersion < 2) {
  10000. return 1;
  10001. }
  10002. if (texture.samples === samples) {
  10003. return samples;
  10004. }
  10005. var gl = this._gl;
  10006. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10007. // Dispose previous render buffers
  10008. if (texture._depthStencilBuffer) {
  10009. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10010. }
  10011. if (texture._MSAAFramebuffer) {
  10012. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10013. }
  10014. if (texture._MSAARenderBuffer) {
  10015. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10016. }
  10017. if (samples > 1) {
  10018. texture._MSAAFramebuffer = gl.createFramebuffer();
  10019. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10020. var colorRenderbuffer = gl.createRenderbuffer();
  10021. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10022. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  10023. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10024. texture._MSAARenderBuffer = colorRenderbuffer;
  10025. }
  10026. else {
  10027. this.bindUnboundFramebuffer(texture._framebuffer);
  10028. }
  10029. texture.samples = samples;
  10030. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  10031. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10032. this.bindUnboundFramebuffer(null);
  10033. return samples;
  10034. };
  10035. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10036. var gl = this._gl;
  10037. var texture = gl.createTexture();
  10038. var generateMipMaps = true;
  10039. var generateDepthBuffer = true;
  10040. var generateStencilBuffer = false;
  10041. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10042. if (options !== undefined) {
  10043. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  10044. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10045. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10046. if (options.samplingMode !== undefined) {
  10047. samplingMode = options.samplingMode;
  10048. }
  10049. }
  10050. texture.isCube = true;
  10051. texture.references = 1;
  10052. texture.generateMipMaps = generateMipMaps;
  10053. texture.references = 1;
  10054. texture.samples = 1;
  10055. texture.samplingMode = samplingMode;
  10056. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10057. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10058. for (var face = 0; face < 6; face++) {
  10059. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10060. }
  10061. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10062. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10063. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10064. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10065. // Create the framebuffer
  10066. var framebuffer = gl.createFramebuffer();
  10067. this.bindUnboundFramebuffer(framebuffer);
  10068. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10069. // Mipmaps
  10070. if (texture.generateMipMaps) {
  10071. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10072. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10073. }
  10074. // Unbind
  10075. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10076. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10077. this.bindUnboundFramebuffer(null);
  10078. texture._framebuffer = framebuffer;
  10079. texture._width = size;
  10080. texture._height = size;
  10081. texture.isReady = true;
  10082. this.resetTextureCache();
  10083. this._loadedTexturesCache.push(texture);
  10084. return texture;
  10085. };
  10086. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  10087. var _this = this;
  10088. if (onLoad === void 0) { onLoad = null; }
  10089. if (onError === void 0) { onError = null; }
  10090. var gl = this._gl;
  10091. var texture = gl.createTexture();
  10092. texture.isCube = true;
  10093. texture.url = rootUrl;
  10094. texture.references = 1;
  10095. texture.onLoadedCallbacks = [];
  10096. var isKTX = false;
  10097. var lastDot = rootUrl.lastIndexOf('.');
  10098. var extension = rootUrl.substring(lastDot).toLowerCase();
  10099. if (this._textureFormatInUse) {
  10100. extension = this._textureFormatInUse;
  10101. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10102. isKTX = true;
  10103. }
  10104. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10105. if (isDDS) {
  10106. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  10107. }
  10108. if (isKTX) {
  10109. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10110. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10111. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10112. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10113. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10114. ktx.uploadLevels(_this._gl, !noMipmap);
  10115. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10116. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10117. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10118. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10119. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10120. _this.resetTextureCache();
  10121. texture._width = ktx.pixelWidth;
  10122. texture._height = ktx.pixelHeight;
  10123. texture.isReady = true;
  10124. }, null, null, true, onError);
  10125. }
  10126. else if (isDDS) {
  10127. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10128. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10129. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10130. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10131. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10132. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  10133. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10134. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10135. }
  10136. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10137. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10138. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10139. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10140. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10141. _this.resetTextureCache();
  10142. texture._width = info.width;
  10143. texture._height = info.height;
  10144. texture.isReady = true;
  10145. }, null, null, true, onError);
  10146. }
  10147. else {
  10148. cascadeLoad(rootUrl, scene, function (imgs) {
  10149. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  10150. var height = width;
  10151. _this._prepareWorkingCanvas();
  10152. _this._workingCanvas.width = width;
  10153. _this._workingCanvas.height = height;
  10154. var faces = [
  10155. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10156. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10157. ];
  10158. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10159. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10160. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10161. for (var index = 0; index < faces.length; index++) {
  10162. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10163. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10164. }
  10165. if (!noMipmap) {
  10166. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10167. }
  10168. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10169. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10170. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10171. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10172. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10173. _this.resetTextureCache();
  10174. texture._width = width;
  10175. texture._height = height;
  10176. texture.isReady = true;
  10177. texture.onLoadedCallbacks.forEach(function (callback) {
  10178. callback();
  10179. });
  10180. if (onLoad) {
  10181. onLoad();
  10182. }
  10183. }, files, onError);
  10184. }
  10185. this._loadedTexturesCache.push(texture);
  10186. return texture;
  10187. };
  10188. Engine.prototype.updateTextureSize = function (texture, width, height) {
  10189. texture._width = width;
  10190. texture._height = height;
  10191. texture._size = width * height;
  10192. texture._baseWidth = width;
  10193. texture._baseHeight = height;
  10194. };
  10195. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  10196. var _this = this;
  10197. if (onLoad === void 0) { onLoad = null; }
  10198. if (onError === void 0) { onError = null; }
  10199. var gl = this._gl;
  10200. var texture = gl.createTexture();
  10201. scene._addPendingData(texture);
  10202. texture.isCube = true;
  10203. texture.references = 1;
  10204. texture.url = url;
  10205. var textureType = gl.UNSIGNED_BYTE;
  10206. if (type === Engine.TEXTURETYPE_FLOAT) {
  10207. textureType = gl.FLOAT;
  10208. }
  10209. var internalFormat = this._getInternalFormat(format);
  10210. var needConversion = false;
  10211. if (internalFormat === gl.RGB) {
  10212. internalFormat = gl.RGBA;
  10213. needConversion = true;
  10214. }
  10215. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10216. var width = size;
  10217. var height = width;
  10218. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  10219. texture._width = width;
  10220. texture._height = height;
  10221. var onerror = function () {
  10222. scene._removePendingData(texture);
  10223. if (onError) {
  10224. onError();
  10225. }
  10226. };
  10227. var internalCallback = function (data) {
  10228. var rgbeDataArrays = callback(data);
  10229. var facesIndex = [
  10230. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10231. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10232. ];
  10233. width = texture._width;
  10234. height = texture._height;
  10235. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  10236. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10237. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10238. if (mipmmapGenerator) {
  10239. var arrayTemp = [];
  10240. // Data are known to be in +X +Y +Z -X -Y -Z
  10241. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  10242. arrayTemp.push(rgbeDataArrays[0]); // +X
  10243. arrayTemp.push(rgbeDataArrays[3]); // -X
  10244. arrayTemp.push(rgbeDataArrays[1]); // +Y
  10245. arrayTemp.push(rgbeDataArrays[4]); // -Y
  10246. arrayTemp.push(rgbeDataArrays[2]); // +Z
  10247. arrayTemp.push(rgbeDataArrays[5]); // -Z
  10248. var mipData = mipmmapGenerator(arrayTemp);
  10249. // mipData is order in +X -X +Y -Y +Z -Z
  10250. var mipFaces = [0, 2, 4, 1, 3, 5];
  10251. for (var level = 0; level < mipData.length; level++) {
  10252. var mipSize = width >> level;
  10253. for (var mipIndex in mipFaces) {
  10254. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  10255. if (needConversion) {
  10256. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10257. }
  10258. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10259. }
  10260. }
  10261. }
  10262. else {
  10263. // Data are known to be in +X +Y +Z -X -Y -Z
  10264. for (var index = 0; index < facesIndex.length; index++) {
  10265. var faceData = rgbeDataArrays[index];
  10266. if (needConversion) {
  10267. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  10268. }
  10269. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  10270. }
  10271. if (!noMipmap && isPot) {
  10272. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10273. }
  10274. else {
  10275. noMipmap = true;
  10276. }
  10277. }
  10278. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  10279. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10280. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10281. }
  10282. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  10283. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10284. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10285. }
  10286. else {
  10287. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10288. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10289. }
  10290. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10291. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10292. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10293. texture.isReady = true;
  10294. _this.resetTextureCache();
  10295. scene._removePendingData(texture);
  10296. if (onLoad) {
  10297. onLoad();
  10298. }
  10299. };
  10300. BABYLON.Tools.LoadFile(url, function (data) {
  10301. internalCallback(data);
  10302. }, onerror, scene.database, true);
  10303. return texture;
  10304. };
  10305. ;
  10306. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10307. // Create new RGBA data container.
  10308. var rgbaData;
  10309. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10310. rgbaData = new Float32Array(width * height * 4);
  10311. }
  10312. else {
  10313. rgbaData = new Uint32Array(width * height * 4);
  10314. }
  10315. // Convert each pixel.
  10316. for (var x = 0; x < width; x++) {
  10317. for (var y = 0; y < height; y++) {
  10318. var index = (y * width + x) * 3;
  10319. var newIndex = (y * width + x) * 4;
  10320. // Map Old Value to new value.
  10321. rgbaData[newIndex + 0] = rgbData[index + 0];
  10322. rgbaData[newIndex + 1] = rgbData[index + 1];
  10323. rgbaData[newIndex + 2] = rgbData[index + 2];
  10324. // Add fully opaque alpha channel.
  10325. rgbaData[newIndex + 3] = 1;
  10326. }
  10327. }
  10328. return rgbaData;
  10329. };
  10330. Engine.prototype._releaseTexture = function (texture) {
  10331. var gl = this._gl;
  10332. if (texture._framebuffer) {
  10333. gl.deleteFramebuffer(texture._framebuffer);
  10334. }
  10335. if (texture._depthStencilBuffer) {
  10336. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10337. }
  10338. if (texture._MSAAFramebuffer) {
  10339. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10340. }
  10341. if (texture._MSAARenderBuffer) {
  10342. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10343. }
  10344. gl.deleteTexture(texture);
  10345. // Unbind channels
  10346. this.unbindAllTextures();
  10347. var index = this._loadedTexturesCache.indexOf(texture);
  10348. if (index !== -1) {
  10349. this._loadedTexturesCache.splice(index, 1);
  10350. }
  10351. };
  10352. Engine.prototype.setProgram = function (program) {
  10353. if (this._currentProgram !== program) {
  10354. this._gl.useProgram(program);
  10355. this._currentProgram = program;
  10356. }
  10357. };
  10358. Engine.prototype.bindSamplers = function (effect) {
  10359. this.setProgram(effect.getProgram());
  10360. var samplers = effect.getSamplers();
  10361. for (var index = 0; index < samplers.length; index++) {
  10362. var uniform = effect.getUniform(samplers[index]);
  10363. this._gl.uniform1i(uniform, index);
  10364. }
  10365. this._currentEffect = null;
  10366. };
  10367. Engine.prototype.activateTexture = function (texture) {
  10368. if (this._activeTexture !== texture) {
  10369. this._gl.activeTexture(texture);
  10370. this._activeTexture = texture;
  10371. }
  10372. };
  10373. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10374. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10375. this._gl.bindTexture(target, texture);
  10376. this._activeTexturesCache[this._activeTexture] = texture;
  10377. }
  10378. };
  10379. Engine.prototype._bindTexture = function (channel, texture) {
  10380. if (channel < 0) {
  10381. return;
  10382. }
  10383. this.activateTexture(this._gl.TEXTURE0 + channel);
  10384. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10385. };
  10386. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10387. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10388. };
  10389. Engine.prototype.unbindAllTextures = function () {
  10390. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10391. this.activateTexture(this._gl["TEXTURE" + channel]);
  10392. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10393. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10394. }
  10395. };
  10396. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10397. if (channel < 0) {
  10398. return;
  10399. }
  10400. this._gl.uniform1i(uniform, channel);
  10401. this._setTexture(channel, texture);
  10402. };
  10403. Engine.prototype._setTexture = function (channel, texture) {
  10404. // Not ready?
  10405. if (!texture || !texture.isReady()) {
  10406. if (this._activeTexturesCache[channel] != null) {
  10407. this.activateTexture(this._gl["TEXTURE" + channel]);
  10408. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10409. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10410. }
  10411. return;
  10412. }
  10413. // Video
  10414. var alreadyActivated = false;
  10415. if (texture instanceof BABYLON.VideoTexture) {
  10416. this.activateTexture(this._gl["TEXTURE" + channel]);
  10417. alreadyActivated = true;
  10418. texture.update();
  10419. }
  10420. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10421. texture.delayLoad();
  10422. return;
  10423. }
  10424. var internalTexture = texture.getInternalTexture();
  10425. if (this._activeTexturesCache[channel] === internalTexture) {
  10426. return;
  10427. }
  10428. if (!alreadyActivated) {
  10429. this.activateTexture(this._gl["TEXTURE" + channel]);
  10430. }
  10431. if (internalTexture.isCube) {
  10432. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10433. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10434. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10435. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10436. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10437. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10438. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10439. }
  10440. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10441. }
  10442. else {
  10443. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10444. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10445. internalTexture._cachedWrapU = texture.wrapU;
  10446. switch (texture.wrapU) {
  10447. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10448. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10449. break;
  10450. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10451. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10452. break;
  10453. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10454. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10455. break;
  10456. }
  10457. }
  10458. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10459. internalTexture._cachedWrapV = texture.wrapV;
  10460. switch (texture.wrapV) {
  10461. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10462. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10463. break;
  10464. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10465. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10466. break;
  10467. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10468. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10469. break;
  10470. }
  10471. }
  10472. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10473. }
  10474. };
  10475. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10476. if (channel < 0) {
  10477. return;
  10478. }
  10479. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10480. this._textureUnits = new Int32Array(textures.length);
  10481. }
  10482. for (var i = 0; i < textures.length; i++) {
  10483. this._textureUnits[i] = channel + i;
  10484. }
  10485. this._gl.uniform1iv(uniform, this._textureUnits);
  10486. for (var index = 0; index < textures.length; index++) {
  10487. this._setTexture(channel + index, textures[index]);
  10488. }
  10489. };
  10490. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10491. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10492. var value = texture.anisotropicFilteringLevel;
  10493. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10494. value = 1;
  10495. }
  10496. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10497. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10498. texture._cachedAnisotropicFilteringLevel = value;
  10499. }
  10500. };
  10501. Engine.prototype.readPixels = function (x, y, width, height) {
  10502. var data = new Uint8Array(height * width * 4);
  10503. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10504. return data;
  10505. };
  10506. /**
  10507. * Add an externaly attached data from its key.
  10508. * This method call will fail and return false, if such key already exists.
  10509. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10510. * @param key the unique key that identifies the data
  10511. * @param data the data object to associate to the key for this Engine instance
  10512. * @return true if no such key were already present and the data was added successfully, false otherwise
  10513. */
  10514. Engine.prototype.addExternalData = function (key, data) {
  10515. return this._externalData.add(key, data);
  10516. };
  10517. /**
  10518. * Get an externaly attached data from its key
  10519. * @param key the unique key that identifies the data
  10520. * @return the associated data, if present (can be null), or undefined if not present
  10521. */
  10522. Engine.prototype.getExternalData = function (key) {
  10523. return this._externalData.get(key);
  10524. };
  10525. /**
  10526. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10527. * @param key the unique key that identifies the data
  10528. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10529. * @return the associated data, can be null if the factory returned null.
  10530. */
  10531. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10532. return this._externalData.getOrAddWithFactory(key, factory);
  10533. };
  10534. /**
  10535. * Remove an externaly attached data from the Engine instance
  10536. * @param key the unique key that identifies the data
  10537. * @return true if the data was successfully removed, false if it doesn't exist
  10538. */
  10539. Engine.prototype.removeExternalData = function (key) {
  10540. return this._externalData.remove(key);
  10541. };
  10542. Engine.prototype.releaseInternalTexture = function (texture) {
  10543. if (!texture) {
  10544. return;
  10545. }
  10546. texture.references--;
  10547. // Final reference ?
  10548. if (texture.references === 0) {
  10549. var texturesCache = this.getLoadedTexturesCache();
  10550. var index = texturesCache.indexOf(texture);
  10551. if (index > -1) {
  10552. texturesCache.splice(index, 1);
  10553. }
  10554. this._releaseTexture(texture);
  10555. }
  10556. };
  10557. Engine.prototype.unbindAllAttributes = function () {
  10558. if (this._mustWipeVertexAttributes) {
  10559. this._mustWipeVertexAttributes = false;
  10560. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10561. this._gl.disableVertexAttribArray(i);
  10562. this._vertexAttribArraysEnabled[i] = false;
  10563. this._currentBufferPointers[i] = null;
  10564. }
  10565. return;
  10566. }
  10567. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10568. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10569. continue;
  10570. }
  10571. this._gl.disableVertexAttribArray(i);
  10572. this._vertexAttribArraysEnabled[i] = false;
  10573. this._currentBufferPointers[i] = null;
  10574. }
  10575. };
  10576. // Dispose
  10577. Engine.prototype.dispose = function () {
  10578. this.hideLoadingUI();
  10579. this.stopRenderLoop();
  10580. // Release scenes
  10581. while (this.scenes.length) {
  10582. this.scenes[0].dispose();
  10583. }
  10584. // Release audio engine
  10585. Engine.audioEngine.dispose();
  10586. // Release effects
  10587. for (var name in this._compiledEffects) {
  10588. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10589. }
  10590. // Unbind
  10591. this.unbindAllAttributes();
  10592. this._gl = null;
  10593. //WebVR
  10594. this.disableVR();
  10595. // Events
  10596. window.removeEventListener("blur", this._onBlur);
  10597. window.removeEventListener("focus", this._onFocus);
  10598. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10599. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10600. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10601. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10602. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10603. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10604. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10605. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10606. // Remove from Instances
  10607. var index = Engine.Instances.indexOf(this);
  10608. if (index >= 0) {
  10609. Engine.Instances.splice(index, 1);
  10610. }
  10611. };
  10612. // Loading screen
  10613. Engine.prototype.displayLoadingUI = function () {
  10614. this._loadingScreen.displayLoadingUI();
  10615. };
  10616. Engine.prototype.hideLoadingUI = function () {
  10617. this._loadingScreen.hideLoadingUI();
  10618. };
  10619. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10620. get: function () {
  10621. return this._loadingScreen;
  10622. },
  10623. set: function (loadingScreen) {
  10624. this._loadingScreen = loadingScreen;
  10625. },
  10626. enumerable: true,
  10627. configurable: true
  10628. });
  10629. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10630. set: function (text) {
  10631. this._loadingScreen.loadingUIText = text;
  10632. },
  10633. enumerable: true,
  10634. configurable: true
  10635. });
  10636. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10637. set: function (color) {
  10638. this._loadingScreen.loadingUIBackgroundColor = color;
  10639. },
  10640. enumerable: true,
  10641. configurable: true
  10642. });
  10643. Engine.prototype.attachContextLostEvent = function (callback) {
  10644. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10645. };
  10646. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10647. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10648. };
  10649. Engine.prototype.getVertexShaderSource = function (program) {
  10650. var shaders = this._gl.getAttachedShaders(program);
  10651. return this._gl.getShaderSource(shaders[0]);
  10652. };
  10653. Engine.prototype.getFragmentShaderSource = function (program) {
  10654. var shaders = this._gl.getAttachedShaders(program);
  10655. return this._gl.getShaderSource(shaders[1]);
  10656. };
  10657. // FPS
  10658. Engine.prototype.getFps = function () {
  10659. return this.fps;
  10660. };
  10661. Engine.prototype.getDeltaTime = function () {
  10662. return this.deltaTime;
  10663. };
  10664. Engine.prototype._measureFps = function () {
  10665. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10666. var length = this.previousFramesDuration.length;
  10667. if (length >= 2) {
  10668. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10669. }
  10670. if (length >= this.fpsRange) {
  10671. if (length > this.fpsRange) {
  10672. this.previousFramesDuration.splice(0, 1);
  10673. length = this.previousFramesDuration.length;
  10674. }
  10675. var sum = 0;
  10676. for (var id = 0; id < length - 1; id++) {
  10677. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10678. }
  10679. this.fps = 1000.0 / (sum / (length - 1));
  10680. }
  10681. };
  10682. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10683. if (this._webGLVersion > 1) {
  10684. return this._caps.colorBufferFloat;
  10685. }
  10686. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10687. };
  10688. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10689. if (this._webGLVersion > 1) {
  10690. return this._caps.colorBufferFloat;
  10691. }
  10692. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10693. };
  10694. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10695. Engine.prototype._canRenderToFramebuffer = function (type) {
  10696. var gl = this._gl;
  10697. //clear existing errors
  10698. while (gl.getError() !== gl.NO_ERROR) { }
  10699. var successful = true;
  10700. var texture = gl.createTexture();
  10701. gl.bindTexture(gl.TEXTURE_2D, texture);
  10702. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10703. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10704. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10705. var fb = gl.createFramebuffer();
  10706. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10707. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10708. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10709. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10710. successful = successful && (gl.getError() === gl.NO_ERROR);
  10711. //try render by clearing frame buffer's color buffer
  10712. if (successful) {
  10713. gl.clear(gl.COLOR_BUFFER_BIT);
  10714. successful = successful && (gl.getError() === gl.NO_ERROR);
  10715. }
  10716. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10717. if (successful) {
  10718. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10719. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10720. var readFormat = gl.RGBA;
  10721. var readType = gl.UNSIGNED_BYTE;
  10722. var buffer = new Uint8Array(4);
  10723. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10724. successful = successful && (gl.getError() === gl.NO_ERROR);
  10725. }
  10726. //clean up
  10727. gl.deleteTexture(texture);
  10728. gl.deleteFramebuffer(fb);
  10729. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10730. //clear accumulated errors
  10731. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10732. return successful;
  10733. };
  10734. Engine.prototype._getWebGLTextureType = function (type) {
  10735. if (type === Engine.TEXTURETYPE_FLOAT) {
  10736. return this._gl.FLOAT;
  10737. }
  10738. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10739. // Add Half Float Constant.
  10740. return Engine.HALF_FLOAT_OES;
  10741. }
  10742. return this._gl.UNSIGNED_BYTE;
  10743. };
  10744. ;
  10745. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10746. if (this._webGLVersion === 1) {
  10747. return this._gl.RGBA;
  10748. }
  10749. if (type === Engine.TEXTURETYPE_FLOAT) {
  10750. return Engine.RGBA32F;
  10751. }
  10752. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10753. return Engine.RGBA16F;
  10754. }
  10755. return this._gl.RGBA;
  10756. };
  10757. ;
  10758. // Statics
  10759. Engine.isSupported = function () {
  10760. try {
  10761. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10762. if (navigator.isCocoonJS) {
  10763. return true;
  10764. }
  10765. var tempcanvas = document.createElement("canvas");
  10766. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10767. return gl != null && !!window.WebGLRenderingContext;
  10768. }
  10769. catch (e) {
  10770. return false;
  10771. }
  10772. };
  10773. return Engine;
  10774. }());
  10775. Engine.Instances = new Array();
  10776. // Const statics
  10777. Engine._ALPHA_DISABLE = 0;
  10778. Engine._ALPHA_ADD = 1;
  10779. Engine._ALPHA_COMBINE = 2;
  10780. Engine._ALPHA_SUBTRACT = 3;
  10781. Engine._ALPHA_MULTIPLY = 4;
  10782. Engine._ALPHA_MAXIMIZED = 5;
  10783. Engine._ALPHA_ONEONE = 6;
  10784. Engine._ALPHA_PREMULTIPLIED = 7;
  10785. Engine._DELAYLOADSTATE_NONE = 0;
  10786. Engine._DELAYLOADSTATE_LOADED = 1;
  10787. Engine._DELAYLOADSTATE_LOADING = 2;
  10788. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10789. Engine._TEXTUREFORMAT_ALPHA = 0;
  10790. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10791. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10792. Engine._TEXTUREFORMAT_RGB = 4;
  10793. Engine._TEXTUREFORMAT_RGBA = 5;
  10794. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10795. Engine._TEXTURETYPE_FLOAT = 1;
  10796. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10797. // Depht or Stencil test Constants.
  10798. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10799. 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.
  10800. 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.
  10801. 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.
  10802. 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.
  10803. 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.
  10804. 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.
  10805. 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.
  10806. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10807. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10808. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10809. // Stencil Actions Constants.
  10810. Engine._KEEP = 0x1E00;
  10811. Engine._REPLACE = 0x1E01;
  10812. Engine._INCR = 0x1E02;
  10813. Engine._DECR = 0x1E03;
  10814. Engine._INVERT = 0x150A;
  10815. Engine._INCR_WRAP = 0x8507;
  10816. Engine._DECR_WRAP = 0x8508;
  10817. // Updatable statics so stick with vars here
  10818. Engine.CollisionsEpsilon = 0.001;
  10819. Engine.CodeRepository = "src/";
  10820. Engine.ShadersRepository = "src/Shaders/";
  10821. BABYLON.Engine = Engine;
  10822. })(BABYLON || (BABYLON = {}));
  10823. //# sourceMappingURL=babylon.engine.js.map
  10824. /// <reference path="Tools\babylon.decorators.ts" />
  10825. var BABYLON;
  10826. (function (BABYLON) {
  10827. /**
  10828. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10829. */
  10830. var Node = (function () {
  10831. /**
  10832. * @constructor
  10833. * @param {string} name - the name and id to be given to this node
  10834. * @param {BABYLON.Scene} the scene this node will be added to
  10835. */
  10836. function Node(name, scene) {
  10837. this.state = "";
  10838. this.metadata = null;
  10839. this.doNotSerialize = false;
  10840. this.animations = new Array();
  10841. this._ranges = {};
  10842. this._childrenFlag = -1;
  10843. this._isEnabled = true;
  10844. this._isReady = true;
  10845. this._currentRenderId = -1;
  10846. this._parentRenderId = -1;
  10847. /**
  10848. * An event triggered when the mesh is disposed.
  10849. * @type {BABYLON.Observable}
  10850. */
  10851. this.onDisposeObservable = new BABYLON.Observable();
  10852. this.name = name;
  10853. this.id = name;
  10854. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10855. this._initCache();
  10856. }
  10857. Object.defineProperty(Node.prototype, "parent", {
  10858. get: function () {
  10859. return this._parentNode;
  10860. },
  10861. set: function (parent) {
  10862. if (this._parentNode === parent) {
  10863. return;
  10864. }
  10865. if (this._parentNode) {
  10866. var index = this._parentNode._children.indexOf(this);
  10867. if (index !== -1) {
  10868. this._parentNode._children.splice(index, 1);
  10869. }
  10870. }
  10871. this._parentNode = parent;
  10872. if (this._parentNode) {
  10873. if (!this._parentNode._children) {
  10874. this._parentNode._children = new Array();
  10875. }
  10876. this._parentNode._children.push(this);
  10877. }
  10878. },
  10879. enumerable: true,
  10880. configurable: true
  10881. });
  10882. Node.prototype.getClassName = function () {
  10883. return "Node";
  10884. };
  10885. Object.defineProperty(Node.prototype, "onDispose", {
  10886. set: function (callback) {
  10887. if (this._onDisposeObserver) {
  10888. this.onDisposeObservable.remove(this._onDisposeObserver);
  10889. }
  10890. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10891. },
  10892. enumerable: true,
  10893. configurable: true
  10894. });
  10895. Node.prototype.getScene = function () {
  10896. return this._scene;
  10897. };
  10898. Node.prototype.getEngine = function () {
  10899. return this._scene.getEngine();
  10900. };
  10901. // override it in derived class
  10902. Node.prototype.getWorldMatrix = function () {
  10903. return BABYLON.Matrix.Identity();
  10904. };
  10905. // override it in derived class if you add new variables to the cache
  10906. // and call the parent class method
  10907. Node.prototype._initCache = function () {
  10908. this._cache = {};
  10909. this._cache.parent = undefined;
  10910. };
  10911. Node.prototype.updateCache = function (force) {
  10912. if (!force && this.isSynchronized())
  10913. return;
  10914. this._cache.parent = this.parent;
  10915. this._updateCache();
  10916. };
  10917. // override it in derived class if you add new variables to the cache
  10918. // and call the parent class method if !ignoreParentClass
  10919. Node.prototype._updateCache = function (ignoreParentClass) {
  10920. };
  10921. // override it in derived class if you add new variables to the cache
  10922. Node.prototype._isSynchronized = function () {
  10923. return true;
  10924. };
  10925. Node.prototype._markSyncedWithParent = function () {
  10926. this._parentRenderId = this.parent._currentRenderId;
  10927. };
  10928. Node.prototype.isSynchronizedWithParent = function () {
  10929. if (!this.parent) {
  10930. return true;
  10931. }
  10932. if (this._parentRenderId !== this.parent._currentRenderId) {
  10933. return false;
  10934. }
  10935. return this.parent.isSynchronized();
  10936. };
  10937. Node.prototype.isSynchronized = function (updateCache) {
  10938. var check = this.hasNewParent();
  10939. check = check || !this.isSynchronizedWithParent();
  10940. check = check || !this._isSynchronized();
  10941. if (updateCache)
  10942. this.updateCache(true);
  10943. return !check;
  10944. };
  10945. Node.prototype.hasNewParent = function (update) {
  10946. if (this._cache.parent === this.parent)
  10947. return false;
  10948. if (update)
  10949. this._cache.parent = this.parent;
  10950. return true;
  10951. };
  10952. /**
  10953. * Is this node ready to be used/rendered
  10954. * @return {boolean} is it ready
  10955. */
  10956. Node.prototype.isReady = function () {
  10957. return this._isReady;
  10958. };
  10959. /**
  10960. * Is this node enabled.
  10961. * If the node has a parent and is enabled, the parent will be inspected as well.
  10962. * @return {boolean} whether this node (and its parent) is enabled.
  10963. * @see setEnabled
  10964. */
  10965. Node.prototype.isEnabled = function () {
  10966. if (!this._isEnabled) {
  10967. return false;
  10968. }
  10969. if (this.parent) {
  10970. return this.parent.isEnabled();
  10971. }
  10972. return true;
  10973. };
  10974. /**
  10975. * Set the enabled state of this node.
  10976. * @param {boolean} value - the new enabled state
  10977. * @see isEnabled
  10978. */
  10979. Node.prototype.setEnabled = function (value) {
  10980. this._isEnabled = value;
  10981. };
  10982. /**
  10983. * Is this node a descendant of the given node.
  10984. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10985. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10986. * @see parent
  10987. */
  10988. Node.prototype.isDescendantOf = function (ancestor) {
  10989. if (this.parent) {
  10990. if (this.parent === ancestor) {
  10991. return true;
  10992. }
  10993. return this.parent.isDescendantOf(ancestor);
  10994. }
  10995. return false;
  10996. };
  10997. /**
  10998. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10999. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11000. * @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.
  11001. * @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.
  11002. */
  11003. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11004. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11005. if (!this._children) {
  11006. return;
  11007. }
  11008. for (var index = 0; index < this._children.length; index++) {
  11009. var item = this._children[index];
  11010. if (!predicate || predicate(item)) {
  11011. results.push(item);
  11012. }
  11013. if (!directDescendantsOnly) {
  11014. item._getDescendants(results, false, predicate);
  11015. }
  11016. }
  11017. };
  11018. /**
  11019. * Will return all nodes that have this node as ascendant.
  11020. * @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.
  11021. * @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.
  11022. * @return {BABYLON.Node[]} all children nodes of all types.
  11023. */
  11024. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11025. var results = [];
  11026. this._getDescendants(results, directDescendantsOnly, predicate);
  11027. return results;
  11028. };
  11029. /**
  11030. * Get all child-meshes of this node.
  11031. */
  11032. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11033. var results = [];
  11034. this._getDescendants(results, directDecendantsOnly, function (node) {
  11035. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11036. });
  11037. return results;
  11038. };
  11039. /**
  11040. * Get all direct children of this node.
  11041. */
  11042. Node.prototype.getChildren = function (predicate) {
  11043. return this.getDescendants(true, predicate);
  11044. };
  11045. Node.prototype._setReady = function (state) {
  11046. if (state === this._isReady) {
  11047. return;
  11048. }
  11049. if (!state) {
  11050. this._isReady = false;
  11051. return;
  11052. }
  11053. this._isReady = true;
  11054. if (this.onReady) {
  11055. this.onReady(this);
  11056. }
  11057. };
  11058. Node.prototype.getAnimationByName = function (name) {
  11059. for (var i = 0; i < this.animations.length; i++) {
  11060. var animation = this.animations[i];
  11061. if (animation.name === name) {
  11062. return animation;
  11063. }
  11064. }
  11065. return null;
  11066. };
  11067. Node.prototype.createAnimationRange = function (name, from, to) {
  11068. // check name not already in use
  11069. if (!this._ranges[name]) {
  11070. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11071. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11072. if (this.animations[i]) {
  11073. this.animations[i].createRange(name, from, to);
  11074. }
  11075. }
  11076. }
  11077. };
  11078. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11079. if (deleteFrames === void 0) { deleteFrames = true; }
  11080. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11081. if (this.animations[i]) {
  11082. this.animations[i].deleteRange(name, deleteFrames);
  11083. }
  11084. }
  11085. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11086. };
  11087. Node.prototype.getAnimationRange = function (name) {
  11088. return this._ranges[name];
  11089. };
  11090. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11091. var range = this.getAnimationRange(name);
  11092. if (!range) {
  11093. return null;
  11094. }
  11095. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11096. };
  11097. Node.prototype.serializeAnimationRanges = function () {
  11098. var serializationRanges = [];
  11099. for (var name in this._ranges) {
  11100. var range = {};
  11101. range.name = name;
  11102. range.from = this._ranges[name].from;
  11103. range.to = this._ranges[name].to;
  11104. serializationRanges.push(range);
  11105. }
  11106. return serializationRanges;
  11107. };
  11108. Node.prototype.dispose = function () {
  11109. this.parent = null;
  11110. // Callback
  11111. this.onDisposeObservable.notifyObservers(this);
  11112. this.onDisposeObservable.clear();
  11113. };
  11114. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11115. if (parsedNode.ranges) {
  11116. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11117. var data = parsedNode.ranges[index];
  11118. node.createAnimationRange(data.name, data.from, data.to);
  11119. }
  11120. }
  11121. };
  11122. return Node;
  11123. }());
  11124. __decorate([
  11125. BABYLON.serialize()
  11126. ], Node.prototype, "name", void 0);
  11127. __decorate([
  11128. BABYLON.serialize()
  11129. ], Node.prototype, "id", void 0);
  11130. __decorate([
  11131. BABYLON.serialize()
  11132. ], Node.prototype, "uniqueId", void 0);
  11133. __decorate([
  11134. BABYLON.serialize()
  11135. ], Node.prototype, "state", void 0);
  11136. __decorate([
  11137. BABYLON.serialize()
  11138. ], Node.prototype, "metadata", void 0);
  11139. BABYLON.Node = Node;
  11140. })(BABYLON || (BABYLON = {}));
  11141. //# sourceMappingURL=babylon.node.js.map
  11142. var BABYLON;
  11143. (function (BABYLON) {
  11144. var FilesInput = (function () {
  11145. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  11146. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  11147. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  11148. this._engine = p_engine;
  11149. this._canvas = p_canvas;
  11150. this._currentScene = p_scene;
  11151. this._sceneLoadedCallback = p_sceneLoadedCallback;
  11152. this._progressCallback = p_progressCallback;
  11153. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  11154. this._textureLoadingCallback = p_textureLoadingCallback;
  11155. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  11156. }
  11157. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  11158. var _this = this;
  11159. if (p_elementToMonitor) {
  11160. this._elementToMonitor = p_elementToMonitor;
  11161. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  11162. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  11163. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  11164. }
  11165. };
  11166. FilesInput.prototype.renderFunction = function () {
  11167. if (this._additionnalRenderLoopLogicCallback) {
  11168. this._additionnalRenderLoopLogicCallback();
  11169. }
  11170. if (this._currentScene) {
  11171. if (this._textureLoadingCallback) {
  11172. var remaining = this._currentScene.getWaitingItemsCount();
  11173. if (remaining > 0) {
  11174. this._textureLoadingCallback(remaining);
  11175. }
  11176. }
  11177. this._currentScene.render();
  11178. }
  11179. };
  11180. FilesInput.prototype.drag = function (e) {
  11181. e.stopPropagation();
  11182. e.preventDefault();
  11183. };
  11184. FilesInput.prototype.drop = function (eventDrop) {
  11185. eventDrop.stopPropagation();
  11186. eventDrop.preventDefault();
  11187. this.loadFiles(eventDrop);
  11188. };
  11189. FilesInput.prototype.loadFiles = function (event) {
  11190. if (this._startingProcessingFilesCallback)
  11191. this._startingProcessingFilesCallback();
  11192. // Handling data transfer via drag'n'drop
  11193. if (event && event.dataTransfer && event.dataTransfer.files) {
  11194. this._filesToLoad = event.dataTransfer.files;
  11195. }
  11196. // Handling files from input files
  11197. if (event && event.target && event.target.files) {
  11198. this._filesToLoad = event.target.files;
  11199. }
  11200. if (this._filesToLoad && this._filesToLoad.length > 0) {
  11201. for (var i = 0; i < this._filesToLoad.length; i++) {
  11202. var name_1 = this._filesToLoad[i].name.toLowerCase();
  11203. var extension = name_1.split('.').pop();
  11204. var type = this._filesToLoad[i].type;
  11205. if (extension === "jpg" || extension === "png" || extension === "bmp" || extension === "jpeg" ||
  11206. type === "image/jpeg" || type === "image/png" || type === "image/bmp") {
  11207. FilesInput.FilesTextures[name_1] = this._filesToLoad[i];
  11208. }
  11209. else {
  11210. if ((extension === "babylon" || extension === "stl" || extension === "obj")
  11211. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  11212. this._sceneFileToLoad = this._filesToLoad[i];
  11213. }
  11214. else {
  11215. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  11216. }
  11217. }
  11218. }
  11219. this.reload();
  11220. }
  11221. };
  11222. FilesInput.prototype.reload = function () {
  11223. var _this = this;
  11224. var that = this;
  11225. // If a ".babylon" file has been provided
  11226. if (this._sceneFileToLoad) {
  11227. if (this._currentScene) {
  11228. if (BABYLON.Tools.errorsCount > 0) {
  11229. BABYLON.Tools.ClearLogCache();
  11230. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  11231. }
  11232. this._engine.stopRenderLoop();
  11233. this._currentScene.dispose();
  11234. }
  11235. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  11236. that._currentScene = newScene;
  11237. // Wait for textures and shaders to be ready
  11238. that._currentScene.executeWhenReady(function () {
  11239. // Attach camera to canvas inputs
  11240. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  11241. that._currentScene.createDefaultCameraOrLight();
  11242. }
  11243. that._currentScene.activeCamera.attachControl(that._canvas);
  11244. if (that._sceneLoadedCallback) {
  11245. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  11246. }
  11247. that._engine.runRenderLoop(function () { that.renderFunction(); });
  11248. });
  11249. }, function (progress) {
  11250. if (_this._progressCallback) {
  11251. _this._progressCallback(progress);
  11252. }
  11253. });
  11254. }
  11255. else {
  11256. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  11257. }
  11258. };
  11259. return FilesInput;
  11260. }());
  11261. FilesInput.FilesTextures = new Array();
  11262. FilesInput.FilesToLoad = new Array();
  11263. BABYLON.FilesInput = FilesInput;
  11264. })(BABYLON || (BABYLON = {}));
  11265. //# sourceMappingURL=babylon.filesInput.js.map
  11266. var BABYLON;
  11267. (function (BABYLON) {
  11268. var IntersectionInfo = (function () {
  11269. function IntersectionInfo(bu, bv, distance) {
  11270. this.bu = bu;
  11271. this.bv = bv;
  11272. this.distance = distance;
  11273. this.faceId = 0;
  11274. this.subMeshId = 0;
  11275. }
  11276. return IntersectionInfo;
  11277. }());
  11278. BABYLON.IntersectionInfo = IntersectionInfo;
  11279. var PickingInfo = (function () {
  11280. function PickingInfo() {
  11281. this.hit = false;
  11282. this.distance = 0;
  11283. this.pickedPoint = null;
  11284. this.pickedMesh = null;
  11285. this.bu = 0;
  11286. this.bv = 0;
  11287. this.faceId = -1;
  11288. this.subMeshId = 0;
  11289. this.pickedSprite = null;
  11290. }
  11291. // Methods
  11292. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  11293. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  11294. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  11295. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11296. return null;
  11297. }
  11298. var indices = this.pickedMesh.getIndices();
  11299. var result;
  11300. if (useVerticesNormals) {
  11301. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11302. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  11303. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  11304. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  11305. normal0 = normal0.scale(this.bu);
  11306. normal1 = normal1.scale(this.bv);
  11307. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  11308. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  11309. }
  11310. else {
  11311. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11312. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  11313. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  11314. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  11315. var p1p2 = vertex1.subtract(vertex2);
  11316. var p3p2 = vertex3.subtract(vertex2);
  11317. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  11318. }
  11319. if (useWorldCoordinates) {
  11320. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  11321. }
  11322. return BABYLON.Vector3.Normalize(result);
  11323. };
  11324. PickingInfo.prototype.getTextureCoordinates = function () {
  11325. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11326. return null;
  11327. }
  11328. var indices = this.pickedMesh.getIndices();
  11329. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11330. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  11331. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  11332. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  11333. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  11334. uv1 = uv1.scale(this.bu);
  11335. uv2 = uv2.scale(this.bv);
  11336. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  11337. };
  11338. return PickingInfo;
  11339. }());
  11340. BABYLON.PickingInfo = PickingInfo;
  11341. })(BABYLON || (BABYLON = {}));
  11342. //# sourceMappingURL=babylon.pickingInfo.js.map
  11343. var BABYLON;
  11344. (function (BABYLON) {
  11345. var BoundingSphere = (function () {
  11346. function BoundingSphere(minimum, maximum) {
  11347. this.minimum = minimum;
  11348. this.maximum = maximum;
  11349. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11350. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11351. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11352. this.radius = distance * 0.5;
  11353. this.centerWorld = BABYLON.Vector3.Zero();
  11354. this._update(BABYLON.Matrix.Identity());
  11355. }
  11356. // Methods
  11357. BoundingSphere.prototype._update = function (world) {
  11358. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11359. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11360. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11361. };
  11362. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11363. for (var i = 0; i < 6; i++) {
  11364. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11365. return false;
  11366. }
  11367. return true;
  11368. };
  11369. BoundingSphere.prototype.intersectsPoint = function (point) {
  11370. var x = this.centerWorld.x - point.x;
  11371. var y = this.centerWorld.y - point.y;
  11372. var z = this.centerWorld.z - point.z;
  11373. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11374. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11375. return false;
  11376. return true;
  11377. };
  11378. // Statics
  11379. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11380. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11381. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11382. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11383. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11384. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11385. return false;
  11386. return true;
  11387. };
  11388. return BoundingSphere;
  11389. }());
  11390. BABYLON.BoundingSphere = BoundingSphere;
  11391. })(BABYLON || (BABYLON = {}));
  11392. //# sourceMappingURL=babylon.boundingSphere.js.map
  11393. var BABYLON;
  11394. (function (BABYLON) {
  11395. var BoundingBox = (function () {
  11396. function BoundingBox(minimum, maximum) {
  11397. this.minimum = minimum;
  11398. this.maximum = maximum;
  11399. this.vectors = new Array();
  11400. this.vectorsWorld = new Array();
  11401. // Bounding vectors
  11402. this.vectors.push(this.minimum.clone());
  11403. this.vectors.push(this.maximum.clone());
  11404. this.vectors.push(this.minimum.clone());
  11405. this.vectors[2].x = this.maximum.x;
  11406. this.vectors.push(this.minimum.clone());
  11407. this.vectors[3].y = this.maximum.y;
  11408. this.vectors.push(this.minimum.clone());
  11409. this.vectors[4].z = this.maximum.z;
  11410. this.vectors.push(this.maximum.clone());
  11411. this.vectors[5].z = this.minimum.z;
  11412. this.vectors.push(this.maximum.clone());
  11413. this.vectors[6].x = this.minimum.x;
  11414. this.vectors.push(this.maximum.clone());
  11415. this.vectors[7].y = this.minimum.y;
  11416. // OBB
  11417. this.center = this.maximum.add(this.minimum).scale(0.5);
  11418. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11419. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11420. // World
  11421. for (var index = 0; index < this.vectors.length; index++) {
  11422. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11423. }
  11424. this.minimumWorld = BABYLON.Vector3.Zero();
  11425. this.maximumWorld = BABYLON.Vector3.Zero();
  11426. this.centerWorld = BABYLON.Vector3.Zero();
  11427. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11428. this._update(BABYLON.Matrix.Identity());
  11429. }
  11430. // Methods
  11431. BoundingBox.prototype.getWorldMatrix = function () {
  11432. return this._worldMatrix;
  11433. };
  11434. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11435. this._worldMatrix.copyFrom(matrix);
  11436. return this;
  11437. };
  11438. BoundingBox.prototype._update = function (world) {
  11439. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11440. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11441. for (var index = 0; index < this.vectors.length; index++) {
  11442. var v = this.vectorsWorld[index];
  11443. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11444. if (v.x < this.minimumWorld.x)
  11445. this.minimumWorld.x = v.x;
  11446. if (v.y < this.minimumWorld.y)
  11447. this.minimumWorld.y = v.y;
  11448. if (v.z < this.minimumWorld.z)
  11449. this.minimumWorld.z = v.z;
  11450. if (v.x > this.maximumWorld.x)
  11451. this.maximumWorld.x = v.x;
  11452. if (v.y > this.maximumWorld.y)
  11453. this.maximumWorld.y = v.y;
  11454. if (v.z > this.maximumWorld.z)
  11455. this.maximumWorld.z = v.z;
  11456. }
  11457. // Extend
  11458. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11459. this.extendSizeWorld.scaleInPlace(0.5);
  11460. // OBB
  11461. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11462. this.centerWorld.scaleInPlace(0.5);
  11463. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11464. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11465. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11466. this._worldMatrix = world;
  11467. };
  11468. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11469. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11470. };
  11471. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11472. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11473. };
  11474. BoundingBox.prototype.intersectsPoint = function (point) {
  11475. var delta = -BABYLON.Epsilon;
  11476. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11477. return false;
  11478. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11479. return false;
  11480. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11481. return false;
  11482. return true;
  11483. };
  11484. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11485. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11486. };
  11487. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11488. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11489. return false;
  11490. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11491. return false;
  11492. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11493. return false;
  11494. return true;
  11495. };
  11496. // Statics
  11497. BoundingBox.Intersects = function (box0, box1) {
  11498. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11499. return false;
  11500. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11501. return false;
  11502. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11503. return false;
  11504. return true;
  11505. };
  11506. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11507. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11508. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11509. return (num <= (sphereRadius * sphereRadius));
  11510. };
  11511. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11512. for (var p = 0; p < 6; p++) {
  11513. for (var i = 0; i < 8; i++) {
  11514. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11515. return false;
  11516. }
  11517. }
  11518. }
  11519. return true;
  11520. };
  11521. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11522. for (var p = 0; p < 6; p++) {
  11523. var inCount = 8;
  11524. for (var i = 0; i < 8; i++) {
  11525. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11526. --inCount;
  11527. }
  11528. else {
  11529. break;
  11530. }
  11531. }
  11532. if (inCount === 0)
  11533. return false;
  11534. }
  11535. return true;
  11536. };
  11537. return BoundingBox;
  11538. }());
  11539. BABYLON.BoundingBox = BoundingBox;
  11540. })(BABYLON || (BABYLON = {}));
  11541. //# sourceMappingURL=babylon.boundingBox.js.map
  11542. var BABYLON;
  11543. (function (BABYLON) {
  11544. var computeBoxExtents = function (axis, box) {
  11545. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11546. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11547. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11548. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11549. var r = r0 + r1 + r2;
  11550. return {
  11551. min: p - r,
  11552. max: p + r
  11553. };
  11554. };
  11555. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11556. var axisOverlap = function (axis, box0, box1) {
  11557. var result0 = computeBoxExtents(axis, box0);
  11558. var result1 = computeBoxExtents(axis, box1);
  11559. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11560. };
  11561. var BoundingInfo = (function () {
  11562. function BoundingInfo(minimum, maximum) {
  11563. this.minimum = minimum;
  11564. this.maximum = maximum;
  11565. this._isLocked = false;
  11566. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11567. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11568. }
  11569. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11570. get: function () {
  11571. return this._isLocked;
  11572. },
  11573. set: function (value) {
  11574. this._isLocked = value;
  11575. },
  11576. enumerable: true,
  11577. configurable: true
  11578. });
  11579. // Methods
  11580. BoundingInfo.prototype.update = function (world) {
  11581. if (this._isLocked) {
  11582. return;
  11583. }
  11584. this.boundingBox._update(world);
  11585. this.boundingSphere._update(world);
  11586. };
  11587. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11588. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11589. return false;
  11590. return this.boundingBox.isInFrustum(frustumPlanes);
  11591. };
  11592. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11593. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11594. };
  11595. BoundingInfo.prototype._checkCollision = function (collider) {
  11596. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11597. };
  11598. BoundingInfo.prototype.intersectsPoint = function (point) {
  11599. if (!this.boundingSphere.centerWorld) {
  11600. return false;
  11601. }
  11602. if (!this.boundingSphere.intersectsPoint(point)) {
  11603. return false;
  11604. }
  11605. if (!this.boundingBox.intersectsPoint(point)) {
  11606. return false;
  11607. }
  11608. return true;
  11609. };
  11610. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11611. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11612. return false;
  11613. }
  11614. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11615. return false;
  11616. }
  11617. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11618. return false;
  11619. }
  11620. if (!precise) {
  11621. return true;
  11622. }
  11623. var box0 = this.boundingBox;
  11624. var box1 = boundingInfo.boundingBox;
  11625. if (!axisOverlap(box0.directions[0], box0, box1))
  11626. return false;
  11627. if (!axisOverlap(box0.directions[1], box0, box1))
  11628. return false;
  11629. if (!axisOverlap(box0.directions[2], box0, box1))
  11630. return false;
  11631. if (!axisOverlap(box1.directions[0], box0, box1))
  11632. return false;
  11633. if (!axisOverlap(box1.directions[1], box0, box1))
  11634. return false;
  11635. if (!axisOverlap(box1.directions[2], box0, box1))
  11636. return false;
  11637. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11638. return false;
  11639. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11640. return false;
  11641. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11642. return false;
  11643. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11644. return false;
  11645. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11646. return false;
  11647. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11648. return false;
  11649. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11650. return false;
  11651. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11652. return false;
  11653. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11654. return false;
  11655. return true;
  11656. };
  11657. return BoundingInfo;
  11658. }());
  11659. BABYLON.BoundingInfo = BoundingInfo;
  11660. })(BABYLON || (BABYLON = {}));
  11661. //# sourceMappingURL=babylon.boundingInfo.js.map
  11662. var BABYLON;
  11663. (function (BABYLON) {
  11664. var Ray = (function () {
  11665. function Ray(origin, direction, length) {
  11666. if (length === void 0) { length = Number.MAX_VALUE; }
  11667. this.origin = origin;
  11668. this.direction = direction;
  11669. this.length = length;
  11670. }
  11671. // Methods
  11672. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  11673. var d = 0.0;
  11674. var maxValue = Number.MAX_VALUE;
  11675. var inv;
  11676. var min;
  11677. var max;
  11678. var temp;
  11679. if (Math.abs(this.direction.x) < 0.0000001) {
  11680. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  11681. return false;
  11682. }
  11683. }
  11684. else {
  11685. inv = 1.0 / this.direction.x;
  11686. min = (minimum.x - this.origin.x) * inv;
  11687. max = (maximum.x - this.origin.x) * inv;
  11688. if (max === -Infinity) {
  11689. max = Infinity;
  11690. }
  11691. if (min > max) {
  11692. temp = min;
  11693. min = max;
  11694. max = temp;
  11695. }
  11696. d = Math.max(min, d);
  11697. maxValue = Math.min(max, maxValue);
  11698. if (d > maxValue) {
  11699. return false;
  11700. }
  11701. }
  11702. if (Math.abs(this.direction.y) < 0.0000001) {
  11703. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  11704. return false;
  11705. }
  11706. }
  11707. else {
  11708. inv = 1.0 / this.direction.y;
  11709. min = (minimum.y - this.origin.y) * inv;
  11710. max = (maximum.y - this.origin.y) * inv;
  11711. if (max === -Infinity) {
  11712. max = Infinity;
  11713. }
  11714. if (min > max) {
  11715. temp = min;
  11716. min = max;
  11717. max = temp;
  11718. }
  11719. d = Math.max(min, d);
  11720. maxValue = Math.min(max, maxValue);
  11721. if (d > maxValue) {
  11722. return false;
  11723. }
  11724. }
  11725. if (Math.abs(this.direction.z) < 0.0000001) {
  11726. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  11727. return false;
  11728. }
  11729. }
  11730. else {
  11731. inv = 1.0 / this.direction.z;
  11732. min = (minimum.z - this.origin.z) * inv;
  11733. max = (maximum.z - this.origin.z) * inv;
  11734. if (max === -Infinity) {
  11735. max = Infinity;
  11736. }
  11737. if (min > max) {
  11738. temp = min;
  11739. min = max;
  11740. max = temp;
  11741. }
  11742. d = Math.max(min, d);
  11743. maxValue = Math.min(max, maxValue);
  11744. if (d > maxValue) {
  11745. return false;
  11746. }
  11747. }
  11748. return true;
  11749. };
  11750. Ray.prototype.intersectsBox = function (box) {
  11751. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  11752. };
  11753. Ray.prototype.intersectsSphere = function (sphere) {
  11754. var x = sphere.center.x - this.origin.x;
  11755. var y = sphere.center.y - this.origin.y;
  11756. var z = sphere.center.z - this.origin.z;
  11757. var pyth = (x * x) + (y * y) + (z * z);
  11758. var rr = sphere.radius * sphere.radius;
  11759. if (pyth <= rr) {
  11760. return true;
  11761. }
  11762. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  11763. if (dot < 0.0) {
  11764. return false;
  11765. }
  11766. var temp = pyth - (dot * dot);
  11767. return temp <= rr;
  11768. };
  11769. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  11770. if (!this._edge1) {
  11771. this._edge1 = BABYLON.Vector3.Zero();
  11772. this._edge2 = BABYLON.Vector3.Zero();
  11773. this._pvec = BABYLON.Vector3.Zero();
  11774. this._tvec = BABYLON.Vector3.Zero();
  11775. this._qvec = BABYLON.Vector3.Zero();
  11776. }
  11777. vertex1.subtractToRef(vertex0, this._edge1);
  11778. vertex2.subtractToRef(vertex0, this._edge2);
  11779. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  11780. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  11781. if (det === 0) {
  11782. return null;
  11783. }
  11784. var invdet = 1 / det;
  11785. this.origin.subtractToRef(vertex0, this._tvec);
  11786. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  11787. if (bu < 0 || bu > 1.0) {
  11788. return null;
  11789. }
  11790. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  11791. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  11792. if (bv < 0 || bu + bv > 1.0) {
  11793. return null;
  11794. }
  11795. //check if the distance is longer than the predefined length.
  11796. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  11797. if (distance > this.length) {
  11798. return null;
  11799. }
  11800. return new BABYLON.IntersectionInfo(bu, bv, distance);
  11801. };
  11802. Ray.prototype.intersectsPlane = function (plane) {
  11803. var distance;
  11804. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  11805. if (Math.abs(result1) < 9.99999997475243E-07) {
  11806. return null;
  11807. }
  11808. else {
  11809. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  11810. distance = (-plane.d - result2) / result1;
  11811. if (distance < 0.0) {
  11812. if (distance < -9.99999997475243E-07) {
  11813. return null;
  11814. }
  11815. else {
  11816. return 0;
  11817. }
  11818. }
  11819. return distance;
  11820. }
  11821. };
  11822. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  11823. var tm = BABYLON.Tmp.Matrix[0];
  11824. mesh.getWorldMatrix().invertToRef(tm);
  11825. if (this._tmpRay) {
  11826. Ray.TransformToRef(this, tm, this._tmpRay);
  11827. }
  11828. else {
  11829. this._tmpRay = Ray.Transform(this, tm);
  11830. }
  11831. return mesh.intersects(this._tmpRay, fastCheck);
  11832. };
  11833. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  11834. if (results) {
  11835. results.length = 0;
  11836. }
  11837. else {
  11838. results = [];
  11839. }
  11840. for (var i = 0; i < meshes.length; i++) {
  11841. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  11842. if (pickInfo.hit) {
  11843. results.push(pickInfo);
  11844. }
  11845. }
  11846. results.sort(this._comparePickingInfo);
  11847. return results;
  11848. };
  11849. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  11850. if (pickingInfoA.distance < pickingInfoB.distance) {
  11851. return -1;
  11852. }
  11853. else if (pickingInfoA.distance > pickingInfoB.distance) {
  11854. return 1;
  11855. }
  11856. else {
  11857. return 0;
  11858. }
  11859. };
  11860. /**
  11861. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  11862. * @param sega the first point of the segment to test the intersection against
  11863. * @param segb the second point of the segment to test the intersection against
  11864. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  11865. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  11866. */
  11867. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  11868. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  11869. var u = segb.subtract(sega);
  11870. var v = rsegb.subtract(this.origin);
  11871. var w = sega.subtract(this.origin);
  11872. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  11873. var b = BABYLON.Vector3.Dot(u, v);
  11874. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  11875. var d = BABYLON.Vector3.Dot(u, w);
  11876. var e = BABYLON.Vector3.Dot(v, w);
  11877. var D = a * c - b * b; // always >= 0
  11878. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  11879. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  11880. // compute the line parameters of the two closest points
  11881. if (D < Ray.smallnum) {
  11882. sN = 0.0; // force using point P0 on segment S1
  11883. sD = 1.0; // to prevent possible division by 0.0 later
  11884. tN = e;
  11885. tD = c;
  11886. }
  11887. else {
  11888. sN = (b * e - c * d);
  11889. tN = (a * e - b * d);
  11890. if (sN < 0.0) {
  11891. sN = 0.0;
  11892. tN = e;
  11893. tD = c;
  11894. }
  11895. else if (sN > sD) {
  11896. sN = sD;
  11897. tN = e + b;
  11898. tD = c;
  11899. }
  11900. }
  11901. if (tN < 0.0) {
  11902. tN = 0.0;
  11903. // recompute sc for this edge
  11904. if (-d < 0.0) {
  11905. sN = 0.0;
  11906. }
  11907. else if (-d > a)
  11908. sN = sD;
  11909. else {
  11910. sN = -d;
  11911. sD = a;
  11912. }
  11913. }
  11914. else if (tN > tD) {
  11915. tN = tD;
  11916. // recompute sc for this edge
  11917. if ((-d + b) < 0.0) {
  11918. sN = 0;
  11919. }
  11920. else if ((-d + b) > a) {
  11921. sN = sD;
  11922. }
  11923. else {
  11924. sN = (-d + b);
  11925. sD = a;
  11926. }
  11927. }
  11928. // finally do the division to get sc and tc
  11929. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  11930. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  11931. // get the difference of the two closest points
  11932. var qtc = v.multiplyByFloats(tc, tc, tc);
  11933. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  11934. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  11935. if (isIntersected) {
  11936. return qtc.length();
  11937. }
  11938. return -1;
  11939. };
  11940. // Statics
  11941. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  11942. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  11943. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  11944. var direction = end.subtract(start);
  11945. direction.normalize();
  11946. return new Ray(start, direction);
  11947. };
  11948. /**
  11949. * 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
  11950. * transformed to the given world matrix.
  11951. * @param origin The origin point
  11952. * @param end The end point
  11953. * @param world a matrix to transform the ray to. Default is the identity matrix.
  11954. */
  11955. Ray.CreateNewFromTo = function (origin, end, world) {
  11956. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  11957. var direction = end.subtract(origin);
  11958. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  11959. direction.normalize();
  11960. return Ray.Transform(new Ray(origin, direction, length), world);
  11961. };
  11962. Ray.Transform = function (ray, matrix) {
  11963. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  11964. Ray.TransformToRef(ray, matrix, result);
  11965. return result;
  11966. };
  11967. Ray.TransformToRef = function (ray, matrix, result) {
  11968. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  11969. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  11970. result.length = ray.length;
  11971. var dir = result.direction;
  11972. var len = dir.length();
  11973. if (!(len === 0 || len === 1)) {
  11974. var num = 1.0 / len;
  11975. dir.x *= num;
  11976. dir.y *= num;
  11977. dir.z *= num;
  11978. result.length *= len;
  11979. }
  11980. };
  11981. return Ray;
  11982. }());
  11983. Ray.smallnum = 0.00000001;
  11984. Ray.rayl = 10e8;
  11985. BABYLON.Ray = Ray;
  11986. })(BABYLON || (BABYLON = {}));
  11987. //# sourceMappingURL=babylon.ray.js.map
  11988. var BABYLON;
  11989. (function (BABYLON) {
  11990. var RayHelper = (function () {
  11991. function RayHelper(ray) {
  11992. this.ray = ray;
  11993. }
  11994. RayHelper.CreateAndShow = function (ray, scene, color) {
  11995. var helper = new RayHelper(ray);
  11996. helper.show(scene, color);
  11997. return helper;
  11998. };
  11999. RayHelper.prototype.show = function (scene, color) {
  12000. if (!this._renderFunction) {
  12001. var ray = this.ray;
  12002. this._renderFunction = this._render.bind(this);
  12003. this._scene = scene;
  12004. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  12005. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  12006. this._scene.registerBeforeRender(this._renderFunction);
  12007. }
  12008. if (color) {
  12009. this._renderLine.color.copyFrom(color);
  12010. }
  12011. };
  12012. RayHelper.prototype.hide = function () {
  12013. if (this._renderFunction) {
  12014. this._scene.unregisterBeforeRender(this._renderFunction);
  12015. this._scene = null;
  12016. this._renderFunction = null;
  12017. this._renderLine.dispose();
  12018. this._renderLine = null;
  12019. this._renderPoints = null;
  12020. }
  12021. };
  12022. RayHelper.prototype._render = function () {
  12023. var ray = this.ray;
  12024. var point = this._renderPoints[1];
  12025. var len = Math.min(ray.length, 1000000);
  12026. point.copyFrom(ray.direction);
  12027. point.scaleInPlace(len);
  12028. point.addInPlace(ray.origin);
  12029. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  12030. };
  12031. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  12032. this._attachedToMesh = mesh;
  12033. var ray = this.ray;
  12034. if (!ray.direction) {
  12035. ray.direction = BABYLON.Vector3.Zero();
  12036. }
  12037. if (!ray.origin) {
  12038. ray.origin = BABYLON.Vector3.Zero();
  12039. }
  12040. if (length) {
  12041. ray.length = length;
  12042. }
  12043. if (!meshSpaceOrigin) {
  12044. meshSpaceOrigin = BABYLON.Vector3.Zero();
  12045. }
  12046. if (!meshSpaceDirection) {
  12047. // -1 so that this will work with Mesh.lookAt
  12048. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  12049. }
  12050. if (!this._meshSpaceDirection) {
  12051. this._meshSpaceDirection = meshSpaceDirection.clone();
  12052. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  12053. }
  12054. else {
  12055. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  12056. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  12057. }
  12058. if (!this._updateToMeshFunction) {
  12059. this._updateToMeshFunction = this._updateToMesh.bind(this);
  12060. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  12061. }
  12062. this._updateToMesh();
  12063. };
  12064. RayHelper.prototype.detachFromMesh = function () {
  12065. if (this._attachedToMesh) {
  12066. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  12067. this._attachedToMesh = null;
  12068. this._updateToMeshFunction = null;
  12069. }
  12070. };
  12071. RayHelper.prototype._updateToMesh = function () {
  12072. var ray = this.ray;
  12073. if (this._attachedToMesh._isDisposed) {
  12074. this.detachFromMesh();
  12075. return;
  12076. }
  12077. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  12078. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  12079. };
  12080. RayHelper.prototype.dispose = function () {
  12081. this.hide();
  12082. this.detachFromMesh();
  12083. this.ray = null;
  12084. };
  12085. return RayHelper;
  12086. }());
  12087. BABYLON.RayHelper = RayHelper;
  12088. })(BABYLON || (BABYLON = {}));
  12089. //# sourceMappingURL=babylon.rayHelper.js.map
  12090. var BABYLON;
  12091. (function (BABYLON) {
  12092. var AbstractMesh = (function (_super) {
  12093. __extends(AbstractMesh, _super);
  12094. // Constructor
  12095. function AbstractMesh(name, scene) {
  12096. var _this = _super.call(this, name, scene) || this;
  12097. _this._facetNb = 0; // facet number
  12098. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12099. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12100. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12101. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12102. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12103. _this._subDiv = {
  12104. max: 1,
  12105. X: 1,
  12106. Y: 1,
  12107. Z: 1
  12108. };
  12109. // Events
  12110. /**
  12111. * An event triggered when this mesh collides with another one
  12112. * @type {BABYLON.Observable}
  12113. */
  12114. _this.onCollideObservable = new BABYLON.Observable();
  12115. /**
  12116. * An event triggered when the collision's position changes
  12117. * @type {BABYLON.Observable}
  12118. */
  12119. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12120. /**
  12121. * An event triggered after the world matrix is updated
  12122. * @type {BABYLON.Observable}
  12123. */
  12124. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12125. // Properties
  12126. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12127. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  12128. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  12129. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  12130. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12131. _this.visibility = 1.0;
  12132. _this.alphaIndex = Number.MAX_VALUE;
  12133. _this.infiniteDistance = false;
  12134. _this.isVisible = true;
  12135. _this.isPickable = true;
  12136. _this.showBoundingBox = false;
  12137. _this.showSubMeshesBoundingBox = false;
  12138. _this.isBlocker = false;
  12139. _this.renderingGroupId = 0;
  12140. _this._receiveShadows = false;
  12141. _this.renderOutline = false;
  12142. _this.outlineColor = BABYLON.Color3.Red();
  12143. _this.outlineWidth = 0.02;
  12144. _this.renderOverlay = false;
  12145. _this.overlayColor = BABYLON.Color3.Red();
  12146. _this.overlayAlpha = 0.5;
  12147. _this._hasVertexAlpha = false;
  12148. _this._useVertexColors = true;
  12149. _this._computeBonesUsingShaders = true;
  12150. _this._numBoneInfluencers = 4;
  12151. _this._applyFog = true;
  12152. _this.scalingDeterminant = 1;
  12153. _this.useOctreeForRenderingSelection = true;
  12154. _this.useOctreeForPicking = true;
  12155. _this.useOctreeForCollisions = true;
  12156. _this.layerMask = 0x0FFFFFFF;
  12157. /**
  12158. * True if the mesh must be rendered in any case.
  12159. */
  12160. _this.alwaysSelectAsActiveMesh = false;
  12161. // Collisions
  12162. _this._checkCollisions = false;
  12163. _this._collisionMask = -1;
  12164. _this._collisionGroup = -1;
  12165. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12166. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12167. _this._collider = new BABYLON.Collider();
  12168. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12169. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12170. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12171. // Edges
  12172. _this.edgesWidth = 1;
  12173. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12174. // Cache
  12175. _this._localWorld = BABYLON.Matrix.Zero();
  12176. _this._worldMatrix = BABYLON.Matrix.Zero();
  12177. _this._absolutePosition = BABYLON.Vector3.Zero();
  12178. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12179. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12180. _this._isDirty = false;
  12181. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12182. _this._isDisposed = false;
  12183. _this._renderId = 0;
  12184. _this._intersectionsInProgress = new Array();
  12185. _this._isWorldMatrixFrozen = false;
  12186. _this._unIndexed = false;
  12187. _this._lightSources = new Array();
  12188. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12189. if (collidedMesh === void 0) { collidedMesh = null; }
  12190. //TODO move this to the collision coordinator!
  12191. if (_this.getScene().workerCollisions)
  12192. newPosition.multiplyInPlace(_this._collider.radius);
  12193. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12194. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12195. _this.position.addInPlace(_this._diffPositionForCollisions);
  12196. }
  12197. if (collidedMesh) {
  12198. _this.onCollideObservable.notifyObservers(collidedMesh);
  12199. }
  12200. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12201. };
  12202. _this.getScene().addMesh(_this);
  12203. _this._resyncLightSources();
  12204. return _this;
  12205. }
  12206. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12207. get: function () {
  12208. return AbstractMesh._BILLBOARDMODE_NONE;
  12209. },
  12210. enumerable: true,
  12211. configurable: true
  12212. });
  12213. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12214. get: function () {
  12215. return AbstractMesh._BILLBOARDMODE_X;
  12216. },
  12217. enumerable: true,
  12218. configurable: true
  12219. });
  12220. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12221. get: function () {
  12222. return AbstractMesh._BILLBOARDMODE_Y;
  12223. },
  12224. enumerable: true,
  12225. configurable: true
  12226. });
  12227. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12228. get: function () {
  12229. return AbstractMesh._BILLBOARDMODE_Z;
  12230. },
  12231. enumerable: true,
  12232. configurable: true
  12233. });
  12234. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12235. get: function () {
  12236. return AbstractMesh._BILLBOARDMODE_ALL;
  12237. },
  12238. enumerable: true,
  12239. configurable: true
  12240. });
  12241. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12242. /**
  12243. * Read-only : the number of facets in the mesh
  12244. */
  12245. get: function () {
  12246. return this._facetNb;
  12247. },
  12248. enumerable: true,
  12249. configurable: true
  12250. });
  12251. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12252. /**
  12253. * The number (integer) of subdivisions per axis in the partioning space
  12254. */
  12255. get: function () {
  12256. return this._partitioningSubdivisions;
  12257. },
  12258. set: function (nb) {
  12259. this._partitioningSubdivisions = nb;
  12260. },
  12261. enumerable: true,
  12262. configurable: true
  12263. });
  12264. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12265. /**
  12266. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12267. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12268. */
  12269. get: function () {
  12270. return this._partitioningBBoxRatio;
  12271. },
  12272. set: function (ratio) {
  12273. this._partitioningBBoxRatio = ratio;
  12274. },
  12275. enumerable: true,
  12276. configurable: true
  12277. });
  12278. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12279. /**
  12280. * Read-only boolean : is the feature facetData enabled ?
  12281. */
  12282. get: function () {
  12283. return this._facetDataEnabled;
  12284. },
  12285. enumerable: true,
  12286. configurable: true
  12287. });
  12288. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12289. set: function (callback) {
  12290. if (this._onCollideObserver) {
  12291. this.onCollideObservable.remove(this._onCollideObserver);
  12292. }
  12293. this._onCollideObserver = this.onCollideObservable.add(callback);
  12294. },
  12295. enumerable: true,
  12296. configurable: true
  12297. });
  12298. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12299. set: function (callback) {
  12300. if (this._onCollisionPositionChangeObserver) {
  12301. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12302. }
  12303. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12304. },
  12305. enumerable: true,
  12306. configurable: true
  12307. });
  12308. Object.defineProperty(AbstractMesh.prototype, "material", {
  12309. get: function () {
  12310. return this._material;
  12311. },
  12312. set: function (value) {
  12313. if (this._material === value) {
  12314. return;
  12315. }
  12316. this._material = value;
  12317. if (!this.subMeshes) {
  12318. return;
  12319. }
  12320. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12321. var subMesh = _a[_i];
  12322. subMesh.setEffect(null);
  12323. }
  12324. },
  12325. enumerable: true,
  12326. configurable: true
  12327. });
  12328. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12329. get: function () {
  12330. return this._receiveShadows;
  12331. },
  12332. set: function (value) {
  12333. if (this._receiveShadows === value) {
  12334. return;
  12335. }
  12336. this._receiveShadows = value;
  12337. this._markSubMeshesAsLightDirty();
  12338. },
  12339. enumerable: true,
  12340. configurable: true
  12341. });
  12342. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12343. get: function () {
  12344. return this._hasVertexAlpha;
  12345. },
  12346. set: function (value) {
  12347. if (this._hasVertexAlpha === value) {
  12348. return;
  12349. }
  12350. this._hasVertexAlpha = value;
  12351. this._markSubMeshesAsAttributesDirty();
  12352. },
  12353. enumerable: true,
  12354. configurable: true
  12355. });
  12356. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12357. get: function () {
  12358. return this._useVertexColors;
  12359. },
  12360. set: function (value) {
  12361. if (this._useVertexColors === value) {
  12362. return;
  12363. }
  12364. this._useVertexColors = value;
  12365. this._markSubMeshesAsAttributesDirty();
  12366. },
  12367. enumerable: true,
  12368. configurable: true
  12369. });
  12370. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12371. get: function () {
  12372. return this._computeBonesUsingShaders;
  12373. },
  12374. set: function (value) {
  12375. if (this._computeBonesUsingShaders === value) {
  12376. return;
  12377. }
  12378. this._computeBonesUsingShaders = value;
  12379. this._markSubMeshesAsAttributesDirty();
  12380. },
  12381. enumerable: true,
  12382. configurable: true
  12383. });
  12384. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12385. get: function () {
  12386. return this._numBoneInfluencers;
  12387. },
  12388. set: function (value) {
  12389. if (this._numBoneInfluencers === value) {
  12390. return;
  12391. }
  12392. this._numBoneInfluencers = value;
  12393. this._markSubMeshesAsAttributesDirty();
  12394. },
  12395. enumerable: true,
  12396. configurable: true
  12397. });
  12398. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12399. get: function () {
  12400. return this._applyFog;
  12401. },
  12402. set: function (value) {
  12403. if (this._applyFog === value) {
  12404. return;
  12405. }
  12406. this._applyFog = value;
  12407. this._markSubMeshesAsMiscDirty();
  12408. },
  12409. enumerable: true,
  12410. configurable: true
  12411. });
  12412. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12413. get: function () {
  12414. return this._collisionMask;
  12415. },
  12416. set: function (mask) {
  12417. this._collisionMask = !isNaN(mask) ? mask : -1;
  12418. },
  12419. enumerable: true,
  12420. configurable: true
  12421. });
  12422. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12423. get: function () {
  12424. return this._collisionGroup;
  12425. },
  12426. set: function (mask) {
  12427. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12428. },
  12429. enumerable: true,
  12430. configurable: true
  12431. });
  12432. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12433. get: function () {
  12434. return this._skeleton;
  12435. },
  12436. set: function (value) {
  12437. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12438. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12439. }
  12440. if (value && value.needInitialSkinMatrix) {
  12441. value._registerMeshWithPoseMatrix(this);
  12442. }
  12443. this._skeleton = value;
  12444. if (!this._skeleton) {
  12445. this._bonesTransformMatrices = null;
  12446. }
  12447. this._markSubMeshesAsAttributesDirty();
  12448. },
  12449. enumerable: true,
  12450. configurable: true
  12451. });
  12452. /**
  12453. * Returns the string "AbstractMesh"
  12454. */
  12455. AbstractMesh.prototype.getClassName = function () {
  12456. return "AbstractMesh";
  12457. };
  12458. /**
  12459. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12460. */
  12461. AbstractMesh.prototype.toString = function (fullDetails) {
  12462. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12463. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12464. if (this._skeleton) {
  12465. ret += ", skeleton: " + this._skeleton.name;
  12466. }
  12467. if (fullDetails) {
  12468. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12469. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12470. }
  12471. return ret;
  12472. };
  12473. AbstractMesh.prototype._resyncLightSources = function () {
  12474. this._lightSources.length = 0;
  12475. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12476. var light = _a[_i];
  12477. if (!light.isEnabled()) {
  12478. continue;
  12479. }
  12480. if (light.canAffectMesh(this)) {
  12481. this._lightSources.push(light);
  12482. }
  12483. }
  12484. this._markSubMeshesAsLightDirty();
  12485. };
  12486. AbstractMesh.prototype._resyncLighSource = function (light) {
  12487. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12488. var index = this._lightSources.indexOf(light);
  12489. if (index === -1) {
  12490. if (!isIn) {
  12491. return;
  12492. }
  12493. this._lightSources.push(light);
  12494. }
  12495. else {
  12496. if (isIn) {
  12497. return;
  12498. }
  12499. this._lightSources.splice(index, 1);
  12500. }
  12501. this._markSubMeshesAsLightDirty();
  12502. };
  12503. AbstractMesh.prototype._removeLightSource = function (light) {
  12504. var index = this._lightSources.indexOf(light);
  12505. if (index === -1) {
  12506. return;
  12507. }
  12508. this._lightSources.slice(index, 1);
  12509. };
  12510. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12511. if (!this.subMeshes) {
  12512. return;
  12513. }
  12514. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12515. var subMesh = _a[_i];
  12516. if (subMesh._materialDefines) {
  12517. func(subMesh._materialDefines);
  12518. }
  12519. }
  12520. };
  12521. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12522. this._markSubMeshesAsDirty(function (defines) { return defines._areLightsDirty = true; });
  12523. };
  12524. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12525. this._markSubMeshesAsDirty(function (defines) { return defines._areAttributesDirty = true; });
  12526. };
  12527. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12528. if (!this.subMeshes) {
  12529. return;
  12530. }
  12531. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12532. var subMesh = _a[_i];
  12533. var material = subMesh.getMaterial();
  12534. if (material) {
  12535. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12536. }
  12537. }
  12538. };
  12539. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12540. /**
  12541. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12542. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12543. * Default : (0.0, 0.0, 0.0)
  12544. */
  12545. get: function () {
  12546. return this._rotation;
  12547. },
  12548. set: function (newRotation) {
  12549. this._rotation = newRotation;
  12550. },
  12551. enumerable: true,
  12552. configurable: true
  12553. });
  12554. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12555. /**
  12556. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12557. * Default : (1.0, 1.0, 1.0)
  12558. */
  12559. get: function () {
  12560. return this._scaling;
  12561. },
  12562. set: function (newScaling) {
  12563. this._scaling = newScaling;
  12564. if (this.physicsImpostor) {
  12565. this.physicsImpostor.forceUpdate();
  12566. }
  12567. },
  12568. enumerable: true,
  12569. configurable: true
  12570. });
  12571. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12572. /**
  12573. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12574. * It's null by default.
  12575. * 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)
  12576. */
  12577. get: function () {
  12578. return this._rotationQuaternion;
  12579. },
  12580. set: function (quaternion) {
  12581. this._rotationQuaternion = quaternion;
  12582. //reset the rotation vector.
  12583. if (quaternion && this.rotation.length()) {
  12584. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12585. }
  12586. },
  12587. enumerable: true,
  12588. configurable: true
  12589. });
  12590. // Methods
  12591. /**
  12592. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12593. * Returns the AbstractMesh.
  12594. */
  12595. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12596. this._poseMatrix.copyFrom(matrix);
  12597. return this;
  12598. };
  12599. /**
  12600. * Returns the mesh Pose matrix.
  12601. * Returned object : Matrix
  12602. */
  12603. AbstractMesh.prototype.getPoseMatrix = function () {
  12604. return this._poseMatrix;
  12605. };
  12606. /**
  12607. * Disables the mesh edger rendering mode.
  12608. * Returns the AbstractMesh.
  12609. */
  12610. AbstractMesh.prototype.disableEdgesRendering = function () {
  12611. if (this._edgesRenderer !== undefined) {
  12612. this._edgesRenderer.dispose();
  12613. this._edgesRenderer = undefined;
  12614. }
  12615. return this;
  12616. };
  12617. /**
  12618. * Enables the edge rendering mode on the mesh.
  12619. * This mode makes the mesh edges visible.
  12620. * Returns the AbstractMesh.
  12621. */
  12622. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12623. if (epsilon === void 0) { epsilon = 0.95; }
  12624. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12625. this.disableEdgesRendering();
  12626. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12627. return this;
  12628. };
  12629. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12630. /**
  12631. * Returns true if the mesh is blocked. Used by the class Mesh.
  12632. * Returns the boolean `false` by default.
  12633. */
  12634. get: function () {
  12635. return false;
  12636. },
  12637. enumerable: true,
  12638. configurable: true
  12639. });
  12640. /**
  12641. * Returns the mesh itself by default, used by the class Mesh.
  12642. * Returned type : AbstractMesh
  12643. */
  12644. AbstractMesh.prototype.getLOD = function (camera) {
  12645. return this;
  12646. };
  12647. /**
  12648. * Returns 0 by default, used by the class Mesh.
  12649. * Returns an integer.
  12650. */
  12651. AbstractMesh.prototype.getTotalVertices = function () {
  12652. return 0;
  12653. };
  12654. /**
  12655. * Returns null by default, used by the class Mesh.
  12656. * Returned type : integer array
  12657. */
  12658. AbstractMesh.prototype.getIndices = function () {
  12659. return null;
  12660. };
  12661. /**
  12662. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12663. * Returned type : float array or Float32Array
  12664. */
  12665. AbstractMesh.prototype.getVerticesData = function (kind) {
  12666. return null;
  12667. };
  12668. /** Returns false by default, used by the class Mesh.
  12669. * Returns a boolean
  12670. */
  12671. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12672. return false;
  12673. };
  12674. /**
  12675. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12676. * Returns a BoundingInfo
  12677. */
  12678. AbstractMesh.prototype.getBoundingInfo = function () {
  12679. if (this._masterMesh) {
  12680. return this._masterMesh.getBoundingInfo();
  12681. }
  12682. if (!this._boundingInfo) {
  12683. this._updateBoundingInfo();
  12684. }
  12685. return this._boundingInfo;
  12686. };
  12687. /**
  12688. * Sets a mesh new object BoundingInfo.
  12689. * Returns the AbstractMesh.
  12690. */
  12691. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12692. this._boundingInfo = boundingInfo;
  12693. return this;
  12694. };
  12695. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12696. get: function () {
  12697. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12698. },
  12699. enumerable: true,
  12700. configurable: true
  12701. });
  12702. AbstractMesh.prototype._preActivate = function () {
  12703. };
  12704. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12705. };
  12706. AbstractMesh.prototype._activate = function (renderId) {
  12707. this._renderId = renderId;
  12708. };
  12709. /**
  12710. * Returns the last update of the World matrix
  12711. * Returns a Matrix.
  12712. */
  12713. AbstractMesh.prototype.getWorldMatrix = function () {
  12714. if (this._masterMesh) {
  12715. return this._masterMesh.getWorldMatrix();
  12716. }
  12717. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12718. this.computeWorldMatrix();
  12719. }
  12720. return this._worldMatrix;
  12721. };
  12722. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12723. /**
  12724. * Returns directly the last state of the mesh World matrix.
  12725. * A Matrix is returned.
  12726. */
  12727. get: function () {
  12728. return this._worldMatrix;
  12729. },
  12730. enumerable: true,
  12731. configurable: true
  12732. });
  12733. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12734. /**
  12735. * Returns the current mesh absolute position.
  12736. * Retuns a Vector3.
  12737. */
  12738. get: function () {
  12739. return this._absolutePosition;
  12740. },
  12741. enumerable: true,
  12742. configurable: true
  12743. });
  12744. /**
  12745. * Prevents the World matrix to be computed any longer.
  12746. * Returns the AbstractMesh.
  12747. */
  12748. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12749. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12750. this.computeWorldMatrix(true);
  12751. this._isWorldMatrixFrozen = true;
  12752. return this;
  12753. };
  12754. /**
  12755. * Allows back the World matrix computation.
  12756. * Returns the AbstractMesh.
  12757. */
  12758. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12759. this._isWorldMatrixFrozen = false;
  12760. this.computeWorldMatrix(true);
  12761. return this;
  12762. };
  12763. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12764. /**
  12765. * True if the World matrix has been frozen.
  12766. * Returns a boolean.
  12767. */
  12768. get: function () {
  12769. return this._isWorldMatrixFrozen;
  12770. },
  12771. enumerable: true,
  12772. configurable: true
  12773. });
  12774. /**
  12775. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12776. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12777. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12778. * The passed axis is also normalized.
  12779. * Returns the AbstractMesh.
  12780. */
  12781. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12782. axis.normalize();
  12783. if (!this.rotationQuaternion) {
  12784. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12785. this.rotation = BABYLON.Vector3.Zero();
  12786. }
  12787. var rotationQuaternion;
  12788. if (!space || space === BABYLON.Space.LOCAL) {
  12789. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12790. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12791. }
  12792. else {
  12793. if (this.parent) {
  12794. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12795. invertParentWorldMatrix.invert();
  12796. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12797. }
  12798. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12799. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12800. }
  12801. return this;
  12802. };
  12803. /**
  12804. * Translates the mesh along the axis vector for the passed distance in the given space.
  12805. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12806. * Returns the AbstractMesh.
  12807. */
  12808. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12809. var displacementVector = axis.scale(distance);
  12810. if (!space || space === BABYLON.Space.LOCAL) {
  12811. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12812. this.setPositionWithLocalVector(tempV3);
  12813. }
  12814. else {
  12815. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12816. }
  12817. return this;
  12818. };
  12819. /**
  12820. * Adds a rotation step to the mesh current rotation.
  12821. * x, y, z are Euler angles expressed in radians.
  12822. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12823. * This means this rotation is made in the mesh local space only.
  12824. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12825. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12826. * ```javascript
  12827. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12828. * ```
  12829. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12830. * 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.
  12831. * Returns the AbstractMesh.
  12832. */
  12833. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12834. var rotationQuaternion;
  12835. if (this.rotationQuaternion) {
  12836. rotationQuaternion = this.rotationQuaternion;
  12837. }
  12838. else {
  12839. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12840. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12841. }
  12842. var accumulation = BABYLON.Tmp.Quaternion[0];
  12843. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12844. rotationQuaternion.multiplyInPlace(accumulation);
  12845. if (!this.rotationQuaternion) {
  12846. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12847. }
  12848. return this;
  12849. };
  12850. /**
  12851. * Retuns the mesh absolute position in the World.
  12852. * Returns a Vector3.
  12853. */
  12854. AbstractMesh.prototype.getAbsolutePosition = function () {
  12855. this.computeWorldMatrix();
  12856. return this._absolutePosition;
  12857. };
  12858. /**
  12859. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12860. * Returns the AbstractMesh.
  12861. */
  12862. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12863. if (!absolutePosition) {
  12864. return;
  12865. }
  12866. var absolutePositionX;
  12867. var absolutePositionY;
  12868. var absolutePositionZ;
  12869. if (absolutePosition.x === undefined) {
  12870. if (arguments.length < 3) {
  12871. return;
  12872. }
  12873. absolutePositionX = arguments[0];
  12874. absolutePositionY = arguments[1];
  12875. absolutePositionZ = arguments[2];
  12876. }
  12877. else {
  12878. absolutePositionX = absolutePosition.x;
  12879. absolutePositionY = absolutePosition.y;
  12880. absolutePositionZ = absolutePosition.z;
  12881. }
  12882. if (this.parent) {
  12883. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12884. invertParentWorldMatrix.invert();
  12885. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12886. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12887. }
  12888. else {
  12889. this.position.x = absolutePositionX;
  12890. this.position.y = absolutePositionY;
  12891. this.position.z = absolutePositionZ;
  12892. }
  12893. return this;
  12894. };
  12895. // ================================== Point of View Movement =================================
  12896. /**
  12897. * Perform relative position change from the point of view of behind the front of the mesh.
  12898. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12899. * Supports definition of mesh facing forward or backward.
  12900. * @param {number} amountRight
  12901. * @param {number} amountUp
  12902. * @param {number} amountForward
  12903. *
  12904. * Returns the AbstractMesh.
  12905. */
  12906. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12907. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12908. return this;
  12909. };
  12910. /**
  12911. * Calculate relative position change from the point of view of behind the front of the mesh.
  12912. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12913. * Supports definition of mesh facing forward or backward.
  12914. * @param {number} amountRight
  12915. * @param {number} amountUp
  12916. * @param {number} amountForward
  12917. *
  12918. * Returns a new Vector3.
  12919. */
  12920. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12921. var rotMatrix = new BABYLON.Matrix();
  12922. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12923. rotQuaternion.toRotationMatrix(rotMatrix);
  12924. var translationDelta = BABYLON.Vector3.Zero();
  12925. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12926. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12927. return translationDelta;
  12928. };
  12929. // ================================== Point of View Rotation =================================
  12930. /**
  12931. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12932. * Supports definition of mesh facing forward or backward.
  12933. * @param {number} flipBack
  12934. * @param {number} twirlClockwise
  12935. * @param {number} tiltRight
  12936. *
  12937. * Returns the AbstractMesh.
  12938. */
  12939. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12940. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12941. return this;
  12942. };
  12943. /**
  12944. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12945. * Supports definition of mesh facing forward or backward.
  12946. * @param {number} flipBack
  12947. * @param {number} twirlClockwise
  12948. * @param {number} tiltRight
  12949. *
  12950. * Returns a new Vector3.
  12951. */
  12952. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12953. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12954. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12955. };
  12956. /**
  12957. * Sets a new pivot matrix to the mesh.
  12958. * Returns the AbstractMesh.
  12959. */
  12960. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12961. this._pivotMatrix = matrix;
  12962. this._cache.pivotMatrixUpdated = true;
  12963. return this;
  12964. };
  12965. /**
  12966. * Returns the mesh pivot matrix.
  12967. * Default : Identity.
  12968. * A Matrix is returned.
  12969. */
  12970. AbstractMesh.prototype.getPivotMatrix = function () {
  12971. return this._pivotMatrix;
  12972. };
  12973. AbstractMesh.prototype._isSynchronized = function () {
  12974. if (this._isDirty) {
  12975. return false;
  12976. }
  12977. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12978. return false;
  12979. if (this._cache.pivotMatrixUpdated) {
  12980. return false;
  12981. }
  12982. if (this.infiniteDistance) {
  12983. return false;
  12984. }
  12985. if (!this._cache.position.equals(this.position))
  12986. return false;
  12987. if (this.rotationQuaternion) {
  12988. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12989. return false;
  12990. }
  12991. if (!this._cache.rotation.equals(this.rotation))
  12992. return false;
  12993. if (!this._cache.scaling.equals(this.scaling))
  12994. return false;
  12995. return true;
  12996. };
  12997. AbstractMesh.prototype._initCache = function () {
  12998. _super.prototype._initCache.call(this);
  12999. this._cache.localMatrixUpdated = false;
  13000. this._cache.position = BABYLON.Vector3.Zero();
  13001. this._cache.scaling = BABYLON.Vector3.Zero();
  13002. this._cache.rotation = BABYLON.Vector3.Zero();
  13003. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13004. this._cache.billboardMode = -1;
  13005. };
  13006. AbstractMesh.prototype.markAsDirty = function (property) {
  13007. if (property === "rotation") {
  13008. this.rotationQuaternion = null;
  13009. }
  13010. this._currentRenderId = Number.MAX_VALUE;
  13011. this._isDirty = true;
  13012. return this;
  13013. };
  13014. /**
  13015. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13016. * Returns the AbstractMesh.
  13017. */
  13018. AbstractMesh.prototype._updateBoundingInfo = function () {
  13019. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13020. this._boundingInfo.update(this.worldMatrixFromCache);
  13021. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13022. return this;
  13023. };
  13024. /**
  13025. * Update a mesh's children BoundingInfo objects only.
  13026. * Returns the AbstractMesh.
  13027. */
  13028. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13029. if (!this.subMeshes) {
  13030. return;
  13031. }
  13032. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13033. var subMesh = this.subMeshes[subIndex];
  13034. if (!subMesh.IsGlobal) {
  13035. subMesh.updateBoundingInfo(matrix);
  13036. }
  13037. }
  13038. return this;
  13039. };
  13040. /**
  13041. * Computes the mesh World matrix and returns it.
  13042. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13043. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13044. * If the parameter `force`is set to `true`, the actual computation is done.
  13045. * Returns the mesh World Matrix.
  13046. */
  13047. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13048. if (this._isWorldMatrixFrozen) {
  13049. return this._worldMatrix;
  13050. }
  13051. if (!force && this.isSynchronized(true)) {
  13052. this._currentRenderId = this.getScene().getRenderId();
  13053. return this._worldMatrix;
  13054. }
  13055. this._cache.position.copyFrom(this.position);
  13056. this._cache.scaling.copyFrom(this.scaling);
  13057. this._cache.pivotMatrixUpdated = false;
  13058. this._cache.billboardMode = this.billboardMode;
  13059. this._currentRenderId = this.getScene().getRenderId();
  13060. this._isDirty = false;
  13061. // Scaling
  13062. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13063. // Rotation
  13064. //rotate, if quaternion is set and rotation was used
  13065. if (this.rotationQuaternion) {
  13066. var len = this.rotation.length();
  13067. if (len) {
  13068. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13069. this.rotation.copyFromFloats(0, 0, 0);
  13070. }
  13071. }
  13072. if (this.rotationQuaternion) {
  13073. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13074. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13075. }
  13076. else {
  13077. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13078. this._cache.rotation.copyFrom(this.rotation);
  13079. }
  13080. // Translation
  13081. if (this.infiniteDistance && !this.parent) {
  13082. var camera = this.getScene().activeCamera;
  13083. if (camera) {
  13084. var cameraWorldMatrix = camera.getWorldMatrix();
  13085. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13086. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13087. }
  13088. }
  13089. else {
  13090. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13091. }
  13092. // Composing transformations
  13093. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13094. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13095. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13096. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13097. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13098. // Need to decompose each rotation here
  13099. var currentPosition = BABYLON.Tmp.Vector3[3];
  13100. if (this.parent && this.parent.getWorldMatrix) {
  13101. if (this._meshToBoneReferal) {
  13102. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13103. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13104. }
  13105. else {
  13106. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13107. }
  13108. }
  13109. else {
  13110. currentPosition.copyFrom(this.position);
  13111. }
  13112. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13113. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13114. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13115. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13116. }
  13117. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13118. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13119. }
  13120. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13121. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13122. }
  13123. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13124. }
  13125. else {
  13126. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13127. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13128. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13129. }
  13130. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13131. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13132. }
  13133. // Local world
  13134. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13135. // Parent
  13136. if (this.parent && this.parent.getWorldMatrix) {
  13137. this._markSyncedWithParent();
  13138. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13139. if (this._meshToBoneReferal) {
  13140. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13141. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13142. }
  13143. else {
  13144. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13145. }
  13146. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13147. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13148. this._worldMatrix.copyFrom(this._localWorld);
  13149. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13150. }
  13151. else {
  13152. if (this._meshToBoneReferal) {
  13153. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13154. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13155. }
  13156. else {
  13157. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13158. }
  13159. }
  13160. }
  13161. else {
  13162. this._worldMatrix.copyFrom(this._localWorld);
  13163. }
  13164. // Bounding info
  13165. this._updateBoundingInfo();
  13166. // Absolute position
  13167. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13168. // Callbacks
  13169. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13170. if (!this._poseMatrix) {
  13171. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13172. }
  13173. return this._worldMatrix;
  13174. };
  13175. /**
  13176. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13177. * @param func: callback function to add
  13178. *
  13179. * Returns the AbstractMesh.
  13180. */
  13181. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13182. this.onAfterWorldMatrixUpdateObservable.add(func);
  13183. return this;
  13184. };
  13185. /**
  13186. * Removes a registered callback function.
  13187. * Returns the AbstractMesh.
  13188. */
  13189. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13190. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13191. return this;
  13192. };
  13193. /**
  13194. * Sets the mesh position in its local space.
  13195. * Returns the AbstractMesh.
  13196. */
  13197. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13198. this.computeWorldMatrix();
  13199. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13200. return this;
  13201. };
  13202. /**
  13203. * Returns the mesh position in the local space from the current World matrix values.
  13204. * Returns a new Vector3.
  13205. */
  13206. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13207. this.computeWorldMatrix();
  13208. var invLocalWorldMatrix = this._localWorld.clone();
  13209. invLocalWorldMatrix.invert();
  13210. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13211. };
  13212. /**
  13213. * Translates the mesh along the passed Vector3 in its local space.
  13214. * Returns the AbstractMesh.
  13215. */
  13216. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13217. this.computeWorldMatrix(true);
  13218. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13219. return this;
  13220. };
  13221. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13222. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13223. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13224. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13225. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13226. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13227. /// <returns>Mesh oriented towards targetMesh</returns>
  13228. if (yawCor === void 0) { yawCor = 0; }
  13229. if (pitchCor === void 0) { pitchCor = 0; }
  13230. if (rollCor === void 0) { rollCor = 0; }
  13231. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13232. var dv = AbstractMesh._lookAtVectorCache;
  13233. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13234. targetPoint.subtractToRef(pos, dv);
  13235. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13236. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13237. var pitch = Math.atan2(dv.y, len);
  13238. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13239. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13240. return this;
  13241. };
  13242. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13243. this._meshToBoneReferal = affectedMesh;
  13244. this.parent = bone;
  13245. if (bone.getWorldMatrix().determinant() < 0) {
  13246. this.scalingDeterminant *= -1;
  13247. }
  13248. return this;
  13249. };
  13250. AbstractMesh.prototype.detachFromBone = function () {
  13251. if (this.parent.getWorldMatrix().determinant() < 0) {
  13252. this.scalingDeterminant *= -1;
  13253. }
  13254. this._meshToBoneReferal = null;
  13255. this.parent = null;
  13256. return this;
  13257. };
  13258. /**
  13259. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13260. * A mesh is in the frustum if its bounding box intersects the frustum.
  13261. * Boolean returned.
  13262. */
  13263. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13264. return this._boundingInfo.isInFrustum(frustumPlanes);
  13265. };
  13266. /**
  13267. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13268. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13269. * Boolean returned.
  13270. */
  13271. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13272. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13273. ;
  13274. };
  13275. /**
  13276. * True if the mesh intersects another mesh or a SolidParticle object.
  13277. * 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)
  13278. * Returns a boolean.
  13279. */
  13280. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13281. if (!this._boundingInfo || !mesh._boundingInfo) {
  13282. return false;
  13283. }
  13284. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13285. };
  13286. /**
  13287. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13288. * Returns a boolean.
  13289. */
  13290. AbstractMesh.prototype.intersectsPoint = function (point) {
  13291. if (!this._boundingInfo) {
  13292. return false;
  13293. }
  13294. return this._boundingInfo.intersectsPoint(point);
  13295. };
  13296. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13297. return this.physicsImpostor;
  13298. };
  13299. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13300. if (!camera) {
  13301. camera = this.getScene().activeCamera;
  13302. }
  13303. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13304. };
  13305. /**
  13306. * Returns the distance from the mesh to the active camera.
  13307. * Returns a float.
  13308. */
  13309. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13310. if (!camera) {
  13311. camera = this.getScene().activeCamera;
  13312. }
  13313. return this.absolutePosition.subtract(camera.position).length();
  13314. };
  13315. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13316. if (!this.physicsImpostor) {
  13317. return;
  13318. }
  13319. this.physicsImpostor.applyImpulse(force, contactPoint);
  13320. return this;
  13321. };
  13322. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13323. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13324. return;
  13325. }
  13326. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13327. mainPivot: pivot1,
  13328. connectedPivot: pivot2,
  13329. nativeParams: options
  13330. });
  13331. return this;
  13332. };
  13333. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13334. // Collisions
  13335. /**
  13336. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13337. * Default `false`.
  13338. */
  13339. get: function () {
  13340. return this._checkCollisions;
  13341. },
  13342. set: function (collisionEnabled) {
  13343. this._checkCollisions = collisionEnabled;
  13344. if (this.getScene().workerCollisions) {
  13345. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13346. }
  13347. },
  13348. enumerable: true,
  13349. configurable: true
  13350. });
  13351. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  13352. var globalPosition = this.getAbsolutePosition();
  13353. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13354. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13355. this._collider.radius = this.ellipsoid;
  13356. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13357. return this;
  13358. };
  13359. // Submeshes octree
  13360. /**
  13361. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13362. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13363. * Returns an Octree of submeshes.
  13364. */
  13365. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13366. if (maxCapacity === void 0) { maxCapacity = 64; }
  13367. if (maxDepth === void 0) { maxDepth = 2; }
  13368. if (!this._submeshesOctree) {
  13369. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13370. }
  13371. this.computeWorldMatrix(true);
  13372. // Update octree
  13373. var bbox = this.getBoundingInfo().boundingBox;
  13374. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13375. return this._submeshesOctree;
  13376. };
  13377. // Collisions
  13378. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13379. this._generatePointsArray();
  13380. // Transformation
  13381. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13382. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13383. subMesh._lastColliderWorldVertices = [];
  13384. subMesh._trianglePlanes = [];
  13385. var start = subMesh.verticesStart;
  13386. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13387. for (var i = start; i < end; i++) {
  13388. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13389. }
  13390. }
  13391. // Collide
  13392. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13393. if (collider.collisionFound) {
  13394. collider.collidedMesh = this;
  13395. }
  13396. return this;
  13397. };
  13398. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13399. var subMeshes;
  13400. var len;
  13401. // Octrees
  13402. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13403. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13404. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13405. len = intersections.length;
  13406. subMeshes = intersections.data;
  13407. }
  13408. else {
  13409. subMeshes = this.subMeshes;
  13410. len = subMeshes.length;
  13411. }
  13412. for (var index = 0; index < len; index++) {
  13413. var subMesh = subMeshes[index];
  13414. // Bounding test
  13415. if (len > 1 && !subMesh._checkCollision(collider))
  13416. continue;
  13417. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13418. }
  13419. return this;
  13420. };
  13421. AbstractMesh.prototype._checkCollision = function (collider) {
  13422. // Bounding box test
  13423. if (!this._boundingInfo._checkCollision(collider))
  13424. return this;
  13425. // Transformation matrix
  13426. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13427. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13428. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13429. return this;
  13430. };
  13431. // Picking
  13432. AbstractMesh.prototype._generatePointsArray = function () {
  13433. return false;
  13434. };
  13435. /**
  13436. * Checks if the passed Ray intersects with the mesh.
  13437. * Returns an object PickingInfo.
  13438. */
  13439. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13440. var pickingInfo = new BABYLON.PickingInfo();
  13441. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13442. return pickingInfo;
  13443. }
  13444. if (!this._generatePointsArray()) {
  13445. return pickingInfo;
  13446. }
  13447. var intersectInfo = null;
  13448. // Octrees
  13449. var subMeshes;
  13450. var len;
  13451. if (this._submeshesOctree && this.useOctreeForPicking) {
  13452. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13453. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13454. len = intersections.length;
  13455. subMeshes = intersections.data;
  13456. }
  13457. else {
  13458. subMeshes = this.subMeshes;
  13459. len = subMeshes.length;
  13460. }
  13461. for (var index = 0; index < len; index++) {
  13462. var subMesh = subMeshes[index];
  13463. // Bounding test
  13464. if (len > 1 && !subMesh.canIntersects(ray))
  13465. continue;
  13466. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13467. if (currentIntersectInfo) {
  13468. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13469. intersectInfo = currentIntersectInfo;
  13470. intersectInfo.subMeshId = index;
  13471. if (fastCheck) {
  13472. break;
  13473. }
  13474. }
  13475. }
  13476. }
  13477. if (intersectInfo) {
  13478. // Get picked point
  13479. var world = this.getWorldMatrix();
  13480. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13481. var direction = ray.direction.clone();
  13482. direction = direction.scale(intersectInfo.distance);
  13483. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13484. var pickedPoint = worldOrigin.add(worldDirection);
  13485. // Return result
  13486. pickingInfo.hit = true;
  13487. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13488. pickingInfo.pickedPoint = pickedPoint;
  13489. pickingInfo.pickedMesh = this;
  13490. pickingInfo.bu = intersectInfo.bu;
  13491. pickingInfo.bv = intersectInfo.bv;
  13492. pickingInfo.faceId = intersectInfo.faceId;
  13493. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13494. return pickingInfo;
  13495. }
  13496. return pickingInfo;
  13497. };
  13498. /**
  13499. * Clones the mesh, used by the class Mesh.
  13500. * Just returns `null` for an AbstractMesh.
  13501. */
  13502. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13503. return null;
  13504. };
  13505. /**
  13506. * Disposes all the mesh submeshes.
  13507. * Returns the AbstractMesh.
  13508. */
  13509. AbstractMesh.prototype.releaseSubMeshes = function () {
  13510. if (this.subMeshes) {
  13511. while (this.subMeshes.length) {
  13512. this.subMeshes[0].dispose();
  13513. }
  13514. }
  13515. else {
  13516. this.subMeshes = new Array();
  13517. }
  13518. return this;
  13519. };
  13520. /**
  13521. * Disposes the AbstractMesh.
  13522. * Some internal references are kept for further use.
  13523. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13524. * Returns nothing.
  13525. */
  13526. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13527. var _this = this;
  13528. var index;
  13529. // Action manager
  13530. if (this.actionManager) {
  13531. this.actionManager.dispose();
  13532. this.actionManager = null;
  13533. }
  13534. // Skeleton
  13535. this.skeleton = null;
  13536. // Animations
  13537. this.getScene().stopAnimation(this);
  13538. // Physics
  13539. if (this.physicsImpostor) {
  13540. this.physicsImpostor.dispose();
  13541. }
  13542. // Intersections in progress
  13543. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13544. var other = this._intersectionsInProgress[index];
  13545. var pos = other._intersectionsInProgress.indexOf(this);
  13546. other._intersectionsInProgress.splice(pos, 1);
  13547. }
  13548. this._intersectionsInProgress = [];
  13549. // Lights
  13550. var lights = this.getScene().lights;
  13551. lights.forEach(function (light) {
  13552. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13553. if (meshIndex !== -1) {
  13554. light.includedOnlyMeshes.splice(meshIndex, 1);
  13555. }
  13556. meshIndex = light.excludedMeshes.indexOf(_this);
  13557. if (meshIndex !== -1) {
  13558. light.excludedMeshes.splice(meshIndex, 1);
  13559. }
  13560. // Shadow generators
  13561. var generator = light.getShadowGenerator();
  13562. if (generator) {
  13563. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  13564. if (meshIndex !== -1) {
  13565. generator.getShadowMap().renderList.splice(meshIndex, 1);
  13566. }
  13567. }
  13568. });
  13569. // Edges
  13570. if (this._edgesRenderer) {
  13571. this._edgesRenderer.dispose();
  13572. this._edgesRenderer = null;
  13573. }
  13574. // SubMeshes
  13575. if (this.getClassName() !== "InstancedMesh") {
  13576. this.releaseSubMeshes();
  13577. }
  13578. // Octree
  13579. var sceneOctree = this.getScene().selectionOctree;
  13580. if (sceneOctree) {
  13581. var index = sceneOctree.dynamicContent.indexOf(this);
  13582. if (index !== -1) {
  13583. sceneOctree.dynamicContent.splice(index, 1);
  13584. }
  13585. }
  13586. // Engine
  13587. this.getScene().getEngine().wipeCaches();
  13588. // Remove from scene
  13589. this.getScene().removeMesh(this);
  13590. if (!doNotRecurse) {
  13591. // Particles
  13592. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13593. if (this.getScene().particleSystems[index].emitter === this) {
  13594. this.getScene().particleSystems[index].dispose();
  13595. index--;
  13596. }
  13597. }
  13598. // Children
  13599. var objects = this.getDescendants(true);
  13600. for (index = 0; index < objects.length; index++) {
  13601. objects[index].dispose();
  13602. }
  13603. }
  13604. else {
  13605. var childMeshes = this.getChildMeshes(true);
  13606. for (index = 0; index < childMeshes.length; index++) {
  13607. var child = childMeshes[index];
  13608. child.parent = null;
  13609. child.computeWorldMatrix(true);
  13610. }
  13611. }
  13612. // facet data
  13613. if (this._facetDataEnabled) {
  13614. this.disableFacetData();
  13615. }
  13616. this.onAfterWorldMatrixUpdateObservable.clear();
  13617. this.onCollideObservable.clear();
  13618. this.onCollisionPositionChangeObservable.clear();
  13619. this._isDisposed = true;
  13620. _super.prototype.dispose.call(this);
  13621. };
  13622. /**
  13623. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13624. * This Vector3 is expressed in the World space.
  13625. */
  13626. AbstractMesh.prototype.getDirection = function (localAxis) {
  13627. var result = BABYLON.Vector3.Zero();
  13628. this.getDirectionToRef(localAxis, result);
  13629. return result;
  13630. };
  13631. /**
  13632. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13633. * localAxis is expressed in the mesh local space.
  13634. * result is computed in the Wordl space from the mesh World matrix.
  13635. * Returns the AbstractMesh.
  13636. */
  13637. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13638. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13639. return this;
  13640. };
  13641. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13642. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13643. if (this.getScene().getRenderId() == 0) {
  13644. this.computeWorldMatrix(true);
  13645. }
  13646. var wm = this.getWorldMatrix();
  13647. if (space == BABYLON.Space.WORLD) {
  13648. var tmat = BABYLON.Tmp.Matrix[0];
  13649. wm.invertToRef(tmat);
  13650. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13651. }
  13652. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13653. this._pivotMatrix.m[12] = -point.x;
  13654. this._pivotMatrix.m[13] = -point.y;
  13655. this._pivotMatrix.m[14] = -point.z;
  13656. this._cache.pivotMatrixUpdated = true;
  13657. return this;
  13658. };
  13659. /**
  13660. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13661. */
  13662. AbstractMesh.prototype.getPivotPoint = function () {
  13663. var point = BABYLON.Vector3.Zero();
  13664. this.getPivotPointToRef(point);
  13665. return point;
  13666. };
  13667. /**
  13668. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13669. * Returns the AbstractMesh.
  13670. */
  13671. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13672. result.x = -this._pivotMatrix.m[12];
  13673. result.y = -this._pivotMatrix.m[13];
  13674. result.z = -this._pivotMatrix.m[14];
  13675. return this;
  13676. };
  13677. /**
  13678. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13679. */
  13680. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13681. var point = BABYLON.Vector3.Zero();
  13682. this.getAbsolutePivotPointToRef(point);
  13683. return point;
  13684. };
  13685. /**
  13686. * Defines the passed mesh as the parent of the current mesh.
  13687. * If keepWorldPositionRotation is set to `true` (default `false`), the current mesh position and rotation are kept.
  13688. * Returns the AbstractMesh.
  13689. */
  13690. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  13691. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13692. var child = this;
  13693. var parent = mesh;
  13694. if (mesh == null) {
  13695. if (child.parent && keepWorldPositionRotation) {
  13696. var rotation = BABYLON.Tmp.Quaternion[0];
  13697. var position = BABYLON.Tmp.Vector3[0];
  13698. var scale = BABYLON.Tmp.Vector3[1];
  13699. child.getWorldMatrix().decompose(scale, rotation, position);
  13700. if (child.rotationQuaternion) {
  13701. child.rotationQuaternion.copyFrom(rotation);
  13702. }
  13703. else {
  13704. rotation.toEulerAnglesToRef(child.rotation);
  13705. }
  13706. child.position.x = position.x;
  13707. child.position.y = position.y;
  13708. child.position.z = position.z;
  13709. }
  13710. }
  13711. else {
  13712. if (keepWorldPositionRotation) {
  13713. var rotation = BABYLON.Tmp.Quaternion[0];
  13714. var position = BABYLON.Tmp.Vector3[0];
  13715. var scale = BABYLON.Tmp.Vector3[1];
  13716. var m1 = BABYLON.Tmp.Matrix[0];
  13717. var m2 = BABYLON.Tmp.Matrix[1];
  13718. parent.getWorldMatrix().decompose(scale, rotation, position);
  13719. rotation.toRotationMatrix(m1);
  13720. m2.setTranslation(position);
  13721. m2.multiplyToRef(m1, m1);
  13722. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13723. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13724. m.decompose(scale, rotation, position);
  13725. if (child.rotationQuaternion) {
  13726. child.rotationQuaternion.copyFrom(rotation);
  13727. }
  13728. else {
  13729. rotation.toEulerAnglesToRef(child.rotation);
  13730. }
  13731. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13732. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13733. m.decompose(scale, rotation, position);
  13734. child.position.x = position.x;
  13735. child.position.y = position.y;
  13736. child.position.z = position.z;
  13737. }
  13738. }
  13739. child.parent = parent;
  13740. return this;
  13741. };
  13742. /**
  13743. * Adds the passed mesh as a child to the current mesh.
  13744. * If keepWorldPositionRotation is set to `true` (default `false`), the child world position and rotation are kept.
  13745. * Returns the AbstractMesh.
  13746. */
  13747. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  13748. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13749. mesh.setParent(this, keepWorldPositionRotation);
  13750. return this;
  13751. };
  13752. /**
  13753. * Removes the passed mesh from the current mesh children list.
  13754. * Returns the AbstractMesh.
  13755. */
  13756. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  13757. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13758. mesh.setParent(null, keepWorldPositionRotation);
  13759. return this;
  13760. };
  13761. /**
  13762. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13763. * Returns the AbstractMesh.
  13764. */
  13765. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13766. result.x = this._pivotMatrix.m[12];
  13767. result.y = this._pivotMatrix.m[13];
  13768. result.z = this._pivotMatrix.m[14];
  13769. this.getPivotPointToRef(result);
  13770. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13771. return this;
  13772. };
  13773. // Facet data
  13774. /**
  13775. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13776. * Returns the AbstractMesh.
  13777. */
  13778. AbstractMesh.prototype._initFacetData = function () {
  13779. if (!this._facetNormals) {
  13780. this._facetNormals = new Array();
  13781. }
  13782. if (!this._facetPositions) {
  13783. this._facetPositions = new Array();
  13784. }
  13785. if (!this._facetPartitioning) {
  13786. this._facetPartitioning = new Array();
  13787. }
  13788. this._facetNb = this.getIndices().length / 3;
  13789. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13790. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13791. for (var f = 0; f < this._facetNb; f++) {
  13792. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13793. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13794. }
  13795. this._facetDataEnabled = true;
  13796. return this;
  13797. };
  13798. /**
  13799. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13800. * This method can be called within the render loop.
  13801. * 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.
  13802. * Returns the AbstractMesh.
  13803. */
  13804. AbstractMesh.prototype.updateFacetData = function () {
  13805. if (!this._facetDataEnabled) {
  13806. this._initFacetData();
  13807. }
  13808. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13809. var indices = this.getIndices();
  13810. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13811. var bInfo = this.getBoundingInfo();
  13812. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13813. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13814. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13815. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13816. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13817. this._subDiv.max = this._partitioningSubdivisions;
  13818. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13819. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13820. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13821. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13822. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13823. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13824. // set the parameters for ComputeNormals()
  13825. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13826. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13827. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13828. this._facetParameters.bInfo = bInfo;
  13829. this._facetParameters.bbSize = this._bbSize;
  13830. this._facetParameters.subDiv = this._subDiv;
  13831. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13832. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13833. return this;
  13834. };
  13835. /**
  13836. * Returns the facetLocalNormals array.
  13837. * The normals are expressed in the mesh local space.
  13838. */
  13839. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13840. if (!this._facetNormals) {
  13841. this.updateFacetData();
  13842. }
  13843. return this._facetNormals;
  13844. };
  13845. /**
  13846. * Returns the facetLocalPositions array.
  13847. * The facet positions are expressed in the mesh local space.
  13848. */
  13849. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13850. if (!this._facetPositions) {
  13851. this.updateFacetData();
  13852. }
  13853. return this._facetPositions;
  13854. };
  13855. /**
  13856. * Returns the facetLocalPartioning array.
  13857. */
  13858. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13859. if (!this._facetPartitioning) {
  13860. this.updateFacetData();
  13861. }
  13862. return this._facetPartitioning;
  13863. };
  13864. /**
  13865. * Returns the i-th facet position in the world system.
  13866. * This method allocates a new Vector3 per call.
  13867. */
  13868. AbstractMesh.prototype.getFacetPosition = function (i) {
  13869. var pos = BABYLON.Vector3.Zero();
  13870. this.getFacetPositionToRef(i, pos);
  13871. return pos;
  13872. };
  13873. /**
  13874. * Sets the reference Vector3 with the i-th facet position in the world system.
  13875. * Returns the AbstractMesh.
  13876. */
  13877. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13878. var localPos = (this.getFacetLocalPositions())[i];
  13879. var world = this.getWorldMatrix();
  13880. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13881. return this;
  13882. };
  13883. /**
  13884. * Returns the i-th facet normal in the world system.
  13885. * This method allocates a new Vector3 per call.
  13886. */
  13887. AbstractMesh.prototype.getFacetNormal = function (i) {
  13888. var norm = BABYLON.Vector3.Zero();
  13889. this.getFacetNormalToRef(i, norm);
  13890. return norm;
  13891. };
  13892. /**
  13893. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13894. * Returns the AbstractMesh.
  13895. */
  13896. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13897. var localNorm = (this.getFacetLocalNormals())[i];
  13898. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13899. return this;
  13900. };
  13901. /**
  13902. * 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).
  13903. */
  13904. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13905. var bInfo = this.getBoundingInfo();
  13906. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13907. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13908. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13909. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13910. return null;
  13911. }
  13912. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13913. };
  13914. /**
  13915. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13916. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13917. * 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.
  13918. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13919. * 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.
  13920. */
  13921. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13922. if (checkFace === void 0) { checkFace = false; }
  13923. if (facing === void 0) { facing = true; }
  13924. var world = this.getWorldMatrix();
  13925. var invMat = BABYLON.Tmp.Matrix[5];
  13926. world.invertToRef(invMat);
  13927. var invVect = BABYLON.Tmp.Vector3[8];
  13928. var closest = null;
  13929. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13930. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13931. if (projected) {
  13932. // tranform the local computed projected vector to world coordinates
  13933. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13934. }
  13935. return closest;
  13936. };
  13937. /**
  13938. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13939. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13940. * 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.
  13941. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13942. * 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.
  13943. */
  13944. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13945. if (checkFace === void 0) { checkFace = false; }
  13946. if (facing === void 0) { facing = true; }
  13947. var closest = null;
  13948. var tmpx = 0.0;
  13949. var tmpy = 0.0;
  13950. var tmpz = 0.0;
  13951. var d = 0.0; // tmp dot facet normal * facet position
  13952. var t0 = 0.0;
  13953. var projx = 0.0;
  13954. var projy = 0.0;
  13955. var projz = 0.0;
  13956. // Get all the facets in the same partitioning block than (x, y, z)
  13957. var facetPositions = this.getFacetLocalPositions();
  13958. var facetNormals = this.getFacetLocalNormals();
  13959. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13960. if (!facetsInBlock) {
  13961. return null;
  13962. }
  13963. // Get the closest facet to (x, y, z)
  13964. var shortest = Number.MAX_VALUE; // init distance vars
  13965. var tmpDistance = shortest;
  13966. var fib; // current facet in the block
  13967. var norm; // current facet normal
  13968. var p0; // current facet barycenter position
  13969. // loop on all the facets in the current partitioning block
  13970. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13971. fib = facetsInBlock[idx];
  13972. norm = facetNormals[fib];
  13973. p0 = facetPositions[fib];
  13974. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13975. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13976. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13977. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13978. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13979. projx = x + norm.x * t0;
  13980. projy = y + norm.y * t0;
  13981. projz = z + norm.z * t0;
  13982. tmpx = projx - x;
  13983. tmpy = projy - y;
  13984. tmpz = projz - z;
  13985. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13986. if (tmpDistance < shortest) {
  13987. shortest = tmpDistance;
  13988. closest = fib;
  13989. if (projected) {
  13990. projected.x = projx;
  13991. projected.y = projy;
  13992. projected.z = projz;
  13993. }
  13994. }
  13995. }
  13996. }
  13997. return closest;
  13998. };
  13999. /**
  14000. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14001. */
  14002. AbstractMesh.prototype.getFacetDataParameters = function () {
  14003. return this._facetParameters;
  14004. };
  14005. /**
  14006. * Disables the feature FacetData and frees the related memory.
  14007. * Returns the AbstractMesh.
  14008. */
  14009. AbstractMesh.prototype.disableFacetData = function () {
  14010. if (this._facetDataEnabled) {
  14011. this._facetDataEnabled = false;
  14012. this._facetPositions = null;
  14013. this._facetNormals = null;
  14014. this._facetPartitioning = null;
  14015. this._facetParameters = null;
  14016. }
  14017. return this;
  14018. };
  14019. return AbstractMesh;
  14020. }(BABYLON.Node));
  14021. // Statics
  14022. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14023. AbstractMesh._BILLBOARDMODE_X = 1;
  14024. AbstractMesh._BILLBOARDMODE_Y = 2;
  14025. AbstractMesh._BILLBOARDMODE_Z = 4;
  14026. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14027. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14028. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14029. BABYLON.AbstractMesh = AbstractMesh;
  14030. })(BABYLON || (BABYLON = {}));
  14031. //# sourceMappingURL=babylon.abstractMesh.js.map
  14032. var BABYLON;
  14033. (function (BABYLON) {
  14034. var Light = (function (_super) {
  14035. __extends(Light, _super);
  14036. /**
  14037. * Creates a Light object in the scene.
  14038. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14039. */
  14040. function Light(name, scene) {
  14041. var _this = _super.call(this, name, scene) || this;
  14042. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14043. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14044. _this.intensity = 1.0;
  14045. _this.range = Number.MAX_VALUE;
  14046. _this._excludeWithLayerMask = 0;
  14047. _this._includeOnlyWithLayerMask = 0;
  14048. _this._lightmapMode = 0;
  14049. // PBR Properties.
  14050. _this.radius = 0.00001;
  14051. _this._excludedMeshesIds = new Array();
  14052. _this._includedOnlyMeshesIds = new Array();
  14053. _this.getScene().addLight(_this);
  14054. _this.includedOnlyMeshes = new Array();
  14055. _this.excludedMeshes = new Array();
  14056. _this._resyncMeshes();
  14057. return _this;
  14058. }
  14059. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14060. /**
  14061. * If every light affecting the material is in this lightmapMode,
  14062. * material.lightmapTexture adds or multiplies
  14063. * (depends on material.useLightmapAsShadowmap)
  14064. * after every other light calculations.
  14065. */
  14066. get: function () {
  14067. return Light._LIGHTMAP_DEFAULT;
  14068. },
  14069. enumerable: true,
  14070. configurable: true
  14071. });
  14072. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14073. /**
  14074. * material.lightmapTexture as only diffuse lighting from this light
  14075. * adds pnly specular lighting from this light
  14076. * adds dynamic shadows
  14077. */
  14078. get: function () {
  14079. return Light._LIGHTMAP_SPECULAR;
  14080. },
  14081. enumerable: true,
  14082. configurable: true
  14083. });
  14084. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14085. /**
  14086. * material.lightmapTexture as only lighting
  14087. * no light calculation from this light
  14088. * only adds dynamic shadows from this light
  14089. */
  14090. get: function () {
  14091. return Light._LIGHTMAP_SHADOWSONLY;
  14092. },
  14093. enumerable: true,
  14094. configurable: true
  14095. });
  14096. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14097. get: function () {
  14098. return this._includedOnlyMeshes;
  14099. },
  14100. set: function (value) {
  14101. this._includedOnlyMeshes = value;
  14102. this._hookArrayForIncludedOnly(value);
  14103. },
  14104. enumerable: true,
  14105. configurable: true
  14106. });
  14107. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14108. get: function () {
  14109. return this._excludedMeshes;
  14110. },
  14111. set: function (value) {
  14112. this._excludedMeshes = value;
  14113. this._hookArrayForExcluded(value);
  14114. },
  14115. enumerable: true,
  14116. configurable: true
  14117. });
  14118. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14119. get: function () {
  14120. return this._excludeWithLayerMask;
  14121. },
  14122. set: function (value) {
  14123. this._excludeWithLayerMask = value;
  14124. this._resyncMeshes();
  14125. },
  14126. enumerable: true,
  14127. configurable: true
  14128. });
  14129. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14130. get: function () {
  14131. return this._includeOnlyWithLayerMask;
  14132. },
  14133. set: function (value) {
  14134. this._includeOnlyWithLayerMask = value;
  14135. this._resyncMeshes();
  14136. },
  14137. enumerable: true,
  14138. configurable: true
  14139. });
  14140. Object.defineProperty(Light.prototype, "lightmapMode", {
  14141. get: function () {
  14142. return this._lightmapMode;
  14143. },
  14144. set: function (value) {
  14145. if (this._lightmapMode === value) {
  14146. return;
  14147. }
  14148. this._lightmapMode = value;
  14149. this._markMeshesAsLightDirty();
  14150. },
  14151. enumerable: true,
  14152. configurable: true
  14153. });
  14154. /**
  14155. * Returns the string "Light".
  14156. */
  14157. Light.prototype.getClassName = function () {
  14158. return "Light";
  14159. };
  14160. /**
  14161. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14162. */
  14163. Light.prototype.toString = function (fullDetails) {
  14164. var ret = "Name: " + this.name;
  14165. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14166. if (this.animations) {
  14167. for (var i = 0; i < this.animations.length; i++) {
  14168. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14169. }
  14170. }
  14171. if (fullDetails) {
  14172. }
  14173. return ret;
  14174. };
  14175. /**
  14176. * Set the enabled state of this node.
  14177. * @param {boolean} value - the new enabled state
  14178. * @see isEnabled
  14179. */
  14180. Light.prototype.setEnabled = function (value) {
  14181. _super.prototype.setEnabled.call(this, value);
  14182. this._resyncMeshes();
  14183. };
  14184. /**
  14185. * Returns the Light associated shadow generator.
  14186. */
  14187. Light.prototype.getShadowGenerator = function () {
  14188. return this._shadowGenerator;
  14189. };
  14190. /**
  14191. * Returns a Vector3, the absolute light position in the World.
  14192. */
  14193. Light.prototype.getAbsolutePosition = function () {
  14194. return BABYLON.Vector3.Zero();
  14195. };
  14196. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  14197. };
  14198. Light.prototype._getWorldMatrix = function () {
  14199. return BABYLON.Matrix.Identity();
  14200. };
  14201. /**
  14202. * Boolean : True if the light will affect the passed mesh.
  14203. */
  14204. Light.prototype.canAffectMesh = function (mesh) {
  14205. if (!mesh) {
  14206. return true;
  14207. }
  14208. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14209. return false;
  14210. }
  14211. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14212. return false;
  14213. }
  14214. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14215. return false;
  14216. }
  14217. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14218. return false;
  14219. }
  14220. return true;
  14221. };
  14222. /**
  14223. * Returns the light World matrix.
  14224. */
  14225. Light.prototype.getWorldMatrix = function () {
  14226. this._currentRenderId = this.getScene().getRenderId();
  14227. var worldMatrix = this._getWorldMatrix();
  14228. if (this.parent && this.parent.getWorldMatrix) {
  14229. if (!this._parentedWorldMatrix) {
  14230. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14231. }
  14232. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14233. this._markSyncedWithParent();
  14234. return this._parentedWorldMatrix;
  14235. }
  14236. return worldMatrix;
  14237. };
  14238. /**
  14239. * Disposes the light.
  14240. */
  14241. Light.prototype.dispose = function () {
  14242. if (this._shadowGenerator) {
  14243. this._shadowGenerator.dispose();
  14244. this._shadowGenerator = null;
  14245. }
  14246. // Animations
  14247. this.getScene().stopAnimation(this);
  14248. // Remove from meshes
  14249. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14250. var mesh = _a[_i];
  14251. mesh._removeLightSource(this);
  14252. }
  14253. // Remove from scene
  14254. this.getScene().removeLight(this);
  14255. _super.prototype.dispose.call(this);
  14256. };
  14257. /**
  14258. * Returns the light type ID (integer).
  14259. */
  14260. Light.prototype.getTypeID = function () {
  14261. return 0;
  14262. };
  14263. /**
  14264. * Returns a new Light object, named "name", from the current one.
  14265. */
  14266. Light.prototype.clone = function (name) {
  14267. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14268. };
  14269. /**
  14270. * Serializes the current light into a Serialization object.
  14271. * Returns the serialized object.
  14272. */
  14273. Light.prototype.serialize = function () {
  14274. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14275. // Type
  14276. serializationObject.type = this.getTypeID();
  14277. // Parent
  14278. if (this.parent) {
  14279. serializationObject.parentId = this.parent.id;
  14280. }
  14281. // Inclusion / exclusions
  14282. if (this.excludedMeshes.length > 0) {
  14283. serializationObject.excludedMeshesIds = [];
  14284. this.excludedMeshes.forEach(function (mesh) {
  14285. serializationObject.excludedMeshesIds.push(mesh.id);
  14286. });
  14287. }
  14288. if (this.includedOnlyMeshes.length > 0) {
  14289. serializationObject.includedOnlyMeshesIds = [];
  14290. this.includedOnlyMeshes.forEach(function (mesh) {
  14291. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14292. });
  14293. }
  14294. // Animations
  14295. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14296. serializationObject.ranges = this.serializeAnimationRanges();
  14297. return serializationObject;
  14298. };
  14299. /**
  14300. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14301. * This new light is named "name" and added to the passed scene.
  14302. */
  14303. Light.GetConstructorFromName = function (type, name, scene) {
  14304. switch (type) {
  14305. case 0:
  14306. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14307. case 1:
  14308. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14309. case 2:
  14310. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14311. case 3:
  14312. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14313. }
  14314. };
  14315. /**
  14316. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14317. */
  14318. Light.Parse = function (parsedLight, scene) {
  14319. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14320. // Inclusion / exclusions
  14321. if (parsedLight.excludedMeshesIds) {
  14322. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14323. }
  14324. if (parsedLight.includedOnlyMeshesIds) {
  14325. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14326. }
  14327. // Parent
  14328. if (parsedLight.parentId) {
  14329. light._waitingParentId = parsedLight.parentId;
  14330. }
  14331. // Animations
  14332. if (parsedLight.animations) {
  14333. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14334. var parsedAnimation = parsedLight.animations[animationIndex];
  14335. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14336. }
  14337. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14338. }
  14339. if (parsedLight.autoAnimate) {
  14340. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14341. }
  14342. return light;
  14343. };
  14344. Light.prototype._hookArrayForExcluded = function (array) {
  14345. var _this = this;
  14346. var oldPush = array.push;
  14347. array.push = function () {
  14348. var items = [];
  14349. for (var _i = 0; _i < arguments.length; _i++) {
  14350. items[_i] = arguments[_i];
  14351. }
  14352. var result = oldPush.apply(array, items);
  14353. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14354. var item = items_1[_a];
  14355. item._resyncLighSource(_this);
  14356. }
  14357. return result;
  14358. };
  14359. var oldSplice = array.splice;
  14360. array.splice = function (index, deleteCount) {
  14361. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14362. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14363. var item = deleted_1[_i];
  14364. item._resyncLighSource(_this);
  14365. }
  14366. return deleted;
  14367. };
  14368. };
  14369. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14370. var _this = this;
  14371. var oldPush = array.push;
  14372. array.push = function () {
  14373. var items = [];
  14374. for (var _i = 0; _i < arguments.length; _i++) {
  14375. items[_i] = arguments[_i];
  14376. }
  14377. var result = oldPush.apply(array, items);
  14378. _this._resyncMeshes();
  14379. return result;
  14380. };
  14381. var oldSplice = array.splice;
  14382. array.splice = function (index, deleteCount) {
  14383. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14384. _this._resyncMeshes();
  14385. return deleted;
  14386. };
  14387. };
  14388. Light.prototype._resyncMeshes = function () {
  14389. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14390. var mesh = _a[_i];
  14391. mesh._resyncLighSource(this);
  14392. }
  14393. };
  14394. Light.prototype._markMeshesAsLightDirty = function () {
  14395. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14396. var mesh = _a[_i];
  14397. if (mesh._lightSources.indexOf(this) !== -1) {
  14398. mesh._markSubMeshesAsLightDirty();
  14399. }
  14400. }
  14401. };
  14402. return Light;
  14403. }(BABYLON.Node));
  14404. //lightmapMode Consts
  14405. Light._LIGHTMAP_DEFAULT = 0;
  14406. Light._LIGHTMAP_SPECULAR = 1;
  14407. Light._LIGHTMAP_SHADOWSONLY = 2;
  14408. __decorate([
  14409. BABYLON.serializeAsColor3()
  14410. ], Light.prototype, "diffuse", void 0);
  14411. __decorate([
  14412. BABYLON.serializeAsColor3()
  14413. ], Light.prototype, "specular", void 0);
  14414. __decorate([
  14415. BABYLON.serialize()
  14416. ], Light.prototype, "intensity", void 0);
  14417. __decorate([
  14418. BABYLON.serialize()
  14419. ], Light.prototype, "range", void 0);
  14420. __decorate([
  14421. BABYLON.serialize("excludeWithLayerMask")
  14422. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14423. __decorate([
  14424. BABYLON.serialize("includeOnlyWithLayerMask")
  14425. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14426. __decorate([
  14427. BABYLON.serialize("lightmapMode")
  14428. ], Light.prototype, "_lightmapMode", void 0);
  14429. __decorate([
  14430. BABYLON.serialize()
  14431. ], Light.prototype, "radius", void 0);
  14432. BABYLON.Light = Light;
  14433. })(BABYLON || (BABYLON = {}));
  14434. //# sourceMappingURL=babylon.light.js.map
  14435. var BABYLON;
  14436. (function (BABYLON) {
  14437. var PointLight = (function (_super) {
  14438. __extends(PointLight, _super);
  14439. /**
  14440. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  14441. * A PointLight emits the light in every direction.
  14442. * It can cast shadows.
  14443. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  14444. * ```javascript
  14445. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  14446. * ```
  14447. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14448. */
  14449. function PointLight(name, position, scene) {
  14450. var _this = _super.call(this, name, scene) || this;
  14451. _this.position = position;
  14452. return _this;
  14453. }
  14454. /**
  14455. * Returns the string "PointLight"
  14456. */
  14457. PointLight.prototype.getClassName = function () {
  14458. return "PointLight";
  14459. };
  14460. /**
  14461. * Returns a Vector3, the PointLight absolute position in the World.
  14462. */
  14463. PointLight.prototype.getAbsolutePosition = function () {
  14464. return this.transformedPosition ? this.transformedPosition : this.position;
  14465. };
  14466. /**
  14467. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  14468. */
  14469. PointLight.prototype.computeTransformedPosition = function () {
  14470. if (this.parent && this.parent.getWorldMatrix) {
  14471. if (!this.transformedPosition) {
  14472. this.transformedPosition = BABYLON.Vector3.Zero();
  14473. }
  14474. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14475. return true;
  14476. }
  14477. return false;
  14478. };
  14479. /**
  14480. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  14481. * Returns the PointLight.
  14482. */
  14483. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  14484. if (this.parent && this.parent.getWorldMatrix) {
  14485. this.computeTransformedPosition();
  14486. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0);
  14487. return this;
  14488. }
  14489. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  14490. return this;
  14491. };
  14492. /**
  14493. * Boolean : returns true by default.
  14494. */
  14495. PointLight.prototype.needCube = function () {
  14496. return true;
  14497. };
  14498. /**
  14499. * Boolean : returns false by default.
  14500. */
  14501. PointLight.prototype.needRefreshPerFrame = function () {
  14502. return false;
  14503. };
  14504. /**
  14505. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  14506. */
  14507. PointLight.prototype.getShadowDirection = function (faceIndex) {
  14508. switch (faceIndex) {
  14509. case 0:
  14510. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  14511. case 1:
  14512. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  14513. case 2:
  14514. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  14515. case 3:
  14516. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  14517. case 4:
  14518. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  14519. case 5:
  14520. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  14521. }
  14522. return BABYLON.Vector3.Zero();
  14523. };
  14524. /**
  14525. * Return the depth scale used for the shadow map.
  14526. */
  14527. PointLight.prototype.getDepthScale = function () {
  14528. return 30.0;
  14529. };
  14530. /**
  14531. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  14532. * - fov = PI / 2
  14533. * - aspect ratio : 1.0
  14534. * - z-near and far equal to the active camera minZ and maxZ.
  14535. * Returns the PointLight.
  14536. */
  14537. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14538. if (this.customProjectionMatrixBuilder) {
  14539. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14540. }
  14541. else {
  14542. var activeCamera = this.getScene().activeCamera;
  14543. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  14544. }
  14545. return this;
  14546. };
  14547. PointLight.prototype._getWorldMatrix = function () {
  14548. if (!this._worldMatrix) {
  14549. this._worldMatrix = BABYLON.Matrix.Identity();
  14550. }
  14551. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14552. return this._worldMatrix;
  14553. };
  14554. /**
  14555. * Returns the integer 0.
  14556. */
  14557. PointLight.prototype.getTypeID = function () {
  14558. return 0;
  14559. };
  14560. return PointLight;
  14561. }(BABYLON.Light));
  14562. __decorate([
  14563. BABYLON.serializeAsVector3()
  14564. ], PointLight.prototype, "position", void 0);
  14565. __decorate([
  14566. BABYLON.serialize()
  14567. ], PointLight.prototype, "shadowMinZ", void 0);
  14568. __decorate([
  14569. BABYLON.serialize()
  14570. ], PointLight.prototype, "shadowMaxZ", void 0);
  14571. BABYLON.PointLight = PointLight;
  14572. })(BABYLON || (BABYLON = {}));
  14573. //# sourceMappingURL=babylon.pointLight.js.map
  14574. var BABYLON;
  14575. (function (BABYLON) {
  14576. var SpotLight = (function (_super) {
  14577. __extends(SpotLight, _super);
  14578. /**
  14579. * Creates a SpotLight object in the scene with the passed parameters :
  14580. * - `position` (Vector3) is the initial SpotLight position,
  14581. * - `direction` (Vector3) is the initial SpotLight direction,
  14582. * - `angle` (float, in radians) is the spot light cone angle,
  14583. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  14584. * A spot light is a simply light oriented cone.
  14585. * It can cast shadows.
  14586. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14587. */
  14588. function SpotLight(name, position, direction, angle, exponent, scene) {
  14589. var _this = _super.call(this, name, scene) || this;
  14590. _this.position = position;
  14591. _this.direction = direction;
  14592. _this.angle = angle;
  14593. _this.exponent = exponent;
  14594. return _this;
  14595. }
  14596. /**
  14597. * Returns the string "SpotLight".
  14598. */
  14599. SpotLight.prototype.getClassName = function () {
  14600. return "SpotLight";
  14601. };
  14602. /**
  14603. * Returns the SpotLight absolute position in the World (Vector3).
  14604. */
  14605. SpotLight.prototype.getAbsolutePosition = function () {
  14606. return this.transformedPosition ? this.transformedPosition : this.position;
  14607. };
  14608. /**
  14609. * Return the depth scale used for the shadow map.
  14610. */
  14611. SpotLight.prototype.getDepthScale = function () {
  14612. return 30.0;
  14613. };
  14614. /**
  14615. * 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.
  14616. * Returns the SpotLight.
  14617. */
  14618. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14619. if (this.customProjectionMatrixBuilder) {
  14620. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14621. }
  14622. else {
  14623. var activeCamera = this.getScene().activeCamera;
  14624. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  14625. }
  14626. return this;
  14627. };
  14628. /**
  14629. * Boolean : false by default.
  14630. */
  14631. SpotLight.prototype.needCube = function () {
  14632. return false;
  14633. };
  14634. /**
  14635. * Boolean : false by default.
  14636. */
  14637. SpotLight.prototype.needRefreshPerFrame = function () {
  14638. return false;
  14639. };
  14640. /**
  14641. * Returns the SpotLight direction (Vector3) for any passed face index.
  14642. */
  14643. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  14644. return this.direction;
  14645. };
  14646. /**
  14647. * Updates the SpotLight direction towards the passed target (Vector3).
  14648. * Returns the updated direction.
  14649. */
  14650. SpotLight.prototype.setDirectionToTarget = function (target) {
  14651. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14652. return this.direction;
  14653. };
  14654. /**
  14655. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  14656. */
  14657. SpotLight.prototype.computeTransformedPosition = function () {
  14658. if (this.parent && this.parent.getWorldMatrix) {
  14659. if (!this.transformedPosition) {
  14660. this.transformedPosition = BABYLON.Vector3.Zero();
  14661. }
  14662. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14663. return true;
  14664. }
  14665. return false;
  14666. };
  14667. /**
  14668. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  14669. * Return the SpotLight.
  14670. */
  14671. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  14672. var normalizeDirection;
  14673. if (this.parent && this.parent.getWorldMatrix) {
  14674. if (!this._transformedDirection) {
  14675. this._transformedDirection = BABYLON.Vector3.Zero();
  14676. }
  14677. this.computeTransformedPosition();
  14678. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14679. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  14680. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  14681. }
  14682. else {
  14683. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  14684. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14685. }
  14686. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  14687. return this;
  14688. };
  14689. SpotLight.prototype._getWorldMatrix = function () {
  14690. if (!this._worldMatrix) {
  14691. this._worldMatrix = BABYLON.Matrix.Identity();
  14692. }
  14693. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14694. return this._worldMatrix;
  14695. };
  14696. /**
  14697. * Returns the integer 2.
  14698. */
  14699. SpotLight.prototype.getTypeID = function () {
  14700. return 2;
  14701. };
  14702. /**
  14703. * Returns the SpotLight rotation (Vector3).
  14704. */
  14705. SpotLight.prototype.getRotation = function () {
  14706. this.direction.normalize();
  14707. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  14708. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  14709. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  14710. };
  14711. return SpotLight;
  14712. }(BABYLON.Light));
  14713. __decorate([
  14714. BABYLON.serializeAsVector3()
  14715. ], SpotLight.prototype, "position", void 0);
  14716. __decorate([
  14717. BABYLON.serializeAsVector3()
  14718. ], SpotLight.prototype, "direction", void 0);
  14719. __decorate([
  14720. BABYLON.serialize()
  14721. ], SpotLight.prototype, "angle", void 0);
  14722. __decorate([
  14723. BABYLON.serialize()
  14724. ], SpotLight.prototype, "exponent", void 0);
  14725. __decorate([
  14726. BABYLON.serialize()
  14727. ], SpotLight.prototype, "shadowMinZ", void 0);
  14728. __decorate([
  14729. BABYLON.serialize()
  14730. ], SpotLight.prototype, "shadowMaxZ", void 0);
  14731. BABYLON.SpotLight = SpotLight;
  14732. })(BABYLON || (BABYLON = {}));
  14733. //# sourceMappingURL=babylon.spotLight.js.map
  14734. var BABYLON;
  14735. (function (BABYLON) {
  14736. var HemisphericLight = (function (_super) {
  14737. __extends(HemisphericLight, _super);
  14738. /**
  14739. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  14740. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  14741. * The HemisphericLight can't cast shadows.
  14742. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14743. */
  14744. function HemisphericLight(name, direction, scene) {
  14745. var _this = _super.call(this, name, scene) || this;
  14746. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  14747. _this.direction = direction;
  14748. return _this;
  14749. }
  14750. /**
  14751. * Returns the string "HemisphericLight".
  14752. */
  14753. HemisphericLight.prototype.getClassName = function () {
  14754. return "HemisphericLight";
  14755. };
  14756. /**
  14757. * Sets the HemisphericLight direction towards the passed target (Vector3).
  14758. * Returns the updated direction.
  14759. */
  14760. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  14761. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  14762. return this.direction;
  14763. };
  14764. HemisphericLight.prototype.getShadowGenerator = function () {
  14765. return null;
  14766. };
  14767. /**
  14768. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  14769. * Returns the HemisphericLight.
  14770. */
  14771. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  14772. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14773. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0);
  14774. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  14775. return this;
  14776. };
  14777. HemisphericLight.prototype._getWorldMatrix = function () {
  14778. if (!this._worldMatrix) {
  14779. this._worldMatrix = BABYLON.Matrix.Identity();
  14780. }
  14781. return this._worldMatrix;
  14782. };
  14783. /**
  14784. * Returns the integer 3.
  14785. */
  14786. HemisphericLight.prototype.getTypeID = function () {
  14787. return 3;
  14788. };
  14789. return HemisphericLight;
  14790. }(BABYLON.Light));
  14791. __decorate([
  14792. BABYLON.serializeAsColor3()
  14793. ], HemisphericLight.prototype, "groundColor", void 0);
  14794. __decorate([
  14795. BABYLON.serializeAsVector3()
  14796. ], HemisphericLight.prototype, "direction", void 0);
  14797. BABYLON.HemisphericLight = HemisphericLight;
  14798. })(BABYLON || (BABYLON = {}));
  14799. //# sourceMappingURL=babylon.hemisphericLight.js.map
  14800. /// <reference path="babylon.light.ts" />
  14801. var BABYLON;
  14802. (function (BABYLON) {
  14803. var DirectionalLight = (function (_super) {
  14804. __extends(DirectionalLight, _super);
  14805. /**
  14806. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  14807. * The directional light is emitted from everywhere in the given direction.
  14808. * It can cast shawdows.
  14809. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14810. */
  14811. function DirectionalLight(name, direction, scene) {
  14812. var _this = _super.call(this, name, scene) || this;
  14813. _this.shadowOrthoScale = 0.5;
  14814. _this.autoUpdateExtends = true;
  14815. // Cache
  14816. _this._orthoLeft = Number.MAX_VALUE;
  14817. _this._orthoRight = Number.MIN_VALUE;
  14818. _this._orthoTop = Number.MIN_VALUE;
  14819. _this._orthoBottom = Number.MAX_VALUE;
  14820. _this.position = direction.scale(-1.0);
  14821. _this.direction = direction;
  14822. return _this;
  14823. }
  14824. /**
  14825. * Returns the string "DirectionalLight".
  14826. */
  14827. DirectionalLight.prototype.getClassName = function () {
  14828. return "DirectionalLight";
  14829. };
  14830. /**
  14831. * Returns the DirectionalLight absolute position in the World.
  14832. */
  14833. DirectionalLight.prototype.getAbsolutePosition = function () {
  14834. return this.transformedPosition ? this.transformedPosition : this.position;
  14835. };
  14836. /**
  14837. * Sets the DirectionalLight direction toward the passed target (Vector3).
  14838. * Returns the updated DirectionalLight direction (Vector3).
  14839. */
  14840. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  14841. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14842. return this.direction;
  14843. };
  14844. /**
  14845. * Return the depth scale used for the shadow map.
  14846. */
  14847. DirectionalLight.prototype.getDepthScale = function () {
  14848. return 30.0;
  14849. };
  14850. /**
  14851. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  14852. * Returns the DirectionalLight.
  14853. */
  14854. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14855. if (this.customProjectionMatrixBuilder) {
  14856. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14857. }
  14858. else {
  14859. var activeCamera = this.getScene().activeCamera;
  14860. // Check extends
  14861. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  14862. var tempVector3 = BABYLON.Vector3.Zero();
  14863. this._orthoLeft = Number.MAX_VALUE;
  14864. this._orthoRight = Number.MIN_VALUE;
  14865. this._orthoTop = Number.MIN_VALUE;
  14866. this._orthoBottom = Number.MAX_VALUE;
  14867. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  14868. var mesh = renderList[meshIndex];
  14869. if (!mesh) {
  14870. continue;
  14871. }
  14872. var boundingInfo = mesh.getBoundingInfo();
  14873. if (!boundingInfo) {
  14874. continue;
  14875. }
  14876. var boundingBox = boundingInfo.boundingBox;
  14877. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  14878. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  14879. if (tempVector3.x < this._orthoLeft)
  14880. this._orthoLeft = tempVector3.x;
  14881. if (tempVector3.y < this._orthoBottom)
  14882. this._orthoBottom = tempVector3.y;
  14883. if (tempVector3.x > this._orthoRight)
  14884. this._orthoRight = tempVector3.x;
  14885. if (tempVector3.y > this._orthoTop)
  14886. this._orthoTop = tempVector3.y;
  14887. }
  14888. }
  14889. }
  14890. var xOffset = this._orthoRight - this._orthoLeft;
  14891. var yOffset = this._orthoTop - this._orthoBottom;
  14892. 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);
  14893. }
  14894. return this;
  14895. };
  14896. /**
  14897. * Boolean : true by default.
  14898. */
  14899. DirectionalLight.prototype.needRefreshPerFrame = function () {
  14900. return true;
  14901. };
  14902. /**
  14903. * Boolean : false by default.
  14904. */
  14905. DirectionalLight.prototype.needCube = function () {
  14906. return false;
  14907. };
  14908. /**
  14909. * Returns the light direction (Vector3) for any passed face index.
  14910. */
  14911. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  14912. return this.direction;
  14913. };
  14914. /**
  14915. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  14916. */
  14917. DirectionalLight.prototype.computeTransformedPosition = function () {
  14918. if (this.parent && this.parent.getWorldMatrix) {
  14919. if (!this.transformedPosition) {
  14920. this.transformedPosition = BABYLON.Vector3.Zero();
  14921. }
  14922. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14923. return true;
  14924. }
  14925. return false;
  14926. };
  14927. /**
  14928. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  14929. * Returns the DirectionalLight.
  14930. */
  14931. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  14932. if (this.parent && this.parent.getWorldMatrix) {
  14933. if (!this._transformedDirection) {
  14934. this._transformedDirection = BABYLON.Vector3.Zero();
  14935. }
  14936. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14937. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  14938. return this;
  14939. }
  14940. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  14941. return this;
  14942. };
  14943. DirectionalLight.prototype._getWorldMatrix = function () {
  14944. if (!this._worldMatrix) {
  14945. this._worldMatrix = BABYLON.Matrix.Identity();
  14946. }
  14947. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14948. return this._worldMatrix;
  14949. };
  14950. /**
  14951. * Returns the integer 1.
  14952. */
  14953. DirectionalLight.prototype.getTypeID = function () {
  14954. return 1;
  14955. };
  14956. return DirectionalLight;
  14957. }(BABYLON.Light));
  14958. __decorate([
  14959. BABYLON.serializeAsVector3()
  14960. ], DirectionalLight.prototype, "position", void 0);
  14961. __decorate([
  14962. BABYLON.serializeAsVector3()
  14963. ], DirectionalLight.prototype, "direction", void 0);
  14964. __decorate([
  14965. BABYLON.serialize()
  14966. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  14967. __decorate([
  14968. BABYLON.serialize()
  14969. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  14970. __decorate([
  14971. BABYLON.serialize()
  14972. ], DirectionalLight.prototype, "shadowMinZ", void 0);
  14973. __decorate([
  14974. BABYLON.serialize()
  14975. ], DirectionalLight.prototype, "shadowMaxZ", void 0);
  14976. BABYLON.DirectionalLight = DirectionalLight;
  14977. })(BABYLON || (BABYLON = {}));
  14978. //# sourceMappingURL=babylon.directionalLight.js.map
  14979. var BABYLON;
  14980. (function (BABYLON) {
  14981. var ShadowGenerator = (function () {
  14982. /**
  14983. * Creates a ShadowGenerator object.
  14984. * A ShadowGenerator is the required tool to use the shadows.
  14985. * Each light casting shadows needs to use its own ShadowGenerator.
  14986. * Required parameters :
  14987. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  14988. * - `light` : the light object generating the shadows.
  14989. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  14990. */
  14991. function ShadowGenerator(mapSize, light) {
  14992. var _this = this;
  14993. // Members
  14994. this._filter = ShadowGenerator.FILTER_NONE;
  14995. this.blurScale = 2;
  14996. this._blurBoxOffset = 0;
  14997. this._bias = 0.00005;
  14998. this._lightDirection = BABYLON.Vector3.Zero();
  14999. this.forceBackFacesOnly = false;
  15000. this._darkness = 0;
  15001. this._transparencyShadow = false;
  15002. this._viewMatrix = BABYLON.Matrix.Zero();
  15003. this._projectionMatrix = BABYLON.Matrix.Zero();
  15004. this._transformMatrix = BABYLON.Matrix.Zero();
  15005. this._worldViewProjection = BABYLON.Matrix.Zero();
  15006. this._currentFaceIndex = 0;
  15007. this._currentFaceIndexCache = 0;
  15008. this._useFullFloat = true;
  15009. this._light = light;
  15010. this._scene = light.getScene();
  15011. this._mapSize = mapSize;
  15012. light._shadowGenerator = this;
  15013. light._markMeshesAsLightDirty();
  15014. // Texture type fallback from float to int if not supported.
  15015. var textureType;
  15016. var caps = this._scene.getEngine().getCaps();
  15017. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  15018. this._useFullFloat = true;
  15019. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  15020. }
  15021. else {
  15022. this._useFullFloat = false;
  15023. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  15024. }
  15025. // Render target
  15026. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  15027. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15028. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15029. this._shadowMap.anisotropicFilteringLevel = 1;
  15030. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  15031. this._shadowMap.renderParticles = false;
  15032. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  15033. _this._currentFaceIndex = faceIndex;
  15034. });
  15035. this._shadowMap.onAfterUnbindObservable.add(function () {
  15036. if (!_this.useBlurExponentialShadowMap) {
  15037. return;
  15038. }
  15039. if (!_this._shadowMap2) {
  15040. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  15041. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15042. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15043. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  15044. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine(), false, textureType);
  15045. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  15046. effect.setTexture("textureSampler", _this._shadowMap);
  15047. });
  15048. _this.blurBoxOffset = 1;
  15049. }
  15050. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  15051. });
  15052. // Custom render function
  15053. var renderSubMesh = function (subMesh) {
  15054. var mesh = subMesh.getRenderingMesh();
  15055. var scene = _this._scene;
  15056. var engine = scene.getEngine();
  15057. // Culling
  15058. engine.setState(subMesh.getMaterial().backFaceCulling);
  15059. // Managing instances
  15060. var batch = mesh._getInstancesRenderList(subMesh._id);
  15061. if (batch.mustReturn) {
  15062. return;
  15063. }
  15064. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15065. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  15066. engine.enableEffect(_this._effect);
  15067. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  15068. var material = subMesh.getMaterial();
  15069. _this._effect.setFloat2("biasAndScale", _this.bias, _this.depthScale);
  15070. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  15071. _this._effect.setVector3("lightPosition", _this.getLight().position);
  15072. if (_this.getLight().needCube()) {
  15073. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  15074. }
  15075. // Alpha test
  15076. if (material && material.needAlphaTesting()) {
  15077. var alphaTexture = material.getAlphaTestTexture();
  15078. _this._effect.setTexture("diffuseSampler", alphaTexture);
  15079. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  15080. }
  15081. // Bones
  15082. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  15083. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  15084. }
  15085. if (_this.forceBackFacesOnly) {
  15086. engine.setState(true, 0, false, true);
  15087. }
  15088. // Draw
  15089. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  15090. if (_this.forceBackFacesOnly) {
  15091. engine.setState(true, 0, false, false);
  15092. }
  15093. }
  15094. else {
  15095. // Need to reset refresh rate of the shadowMap
  15096. _this._shadowMap.resetRefreshCounter();
  15097. }
  15098. };
  15099. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  15100. var index;
  15101. for (index = 0; index < opaqueSubMeshes.length; index++) {
  15102. renderSubMesh(opaqueSubMeshes.data[index]);
  15103. }
  15104. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  15105. renderSubMesh(alphaTestSubMeshes.data[index]);
  15106. }
  15107. if (_this._transparencyShadow) {
  15108. for (index = 0; index < transparentSubMeshes.length; index++) {
  15109. renderSubMesh(transparentSubMeshes.data[index]);
  15110. }
  15111. }
  15112. };
  15113. this._shadowMap.onClearObservable.add(function (engine) {
  15114. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  15115. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  15116. }
  15117. else {
  15118. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  15119. }
  15120. });
  15121. }
  15122. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  15123. // Static
  15124. get: function () {
  15125. return ShadowGenerator._FILTER_NONE;
  15126. },
  15127. enumerable: true,
  15128. configurable: true
  15129. });
  15130. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  15131. get: function () {
  15132. return ShadowGenerator._FILTER_POISSONSAMPLING;
  15133. },
  15134. enumerable: true,
  15135. configurable: true
  15136. });
  15137. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  15138. get: function () {
  15139. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  15140. },
  15141. enumerable: true,
  15142. configurable: true
  15143. });
  15144. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  15145. get: function () {
  15146. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  15147. },
  15148. enumerable: true,
  15149. configurable: true
  15150. });
  15151. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  15152. get: function () {
  15153. return this._bias;
  15154. },
  15155. set: function (bias) {
  15156. this._bias = bias;
  15157. },
  15158. enumerable: true,
  15159. configurable: true
  15160. });
  15161. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  15162. get: function () {
  15163. return this._blurBoxOffset;
  15164. },
  15165. set: function (value) {
  15166. var _this = this;
  15167. if (this._blurBoxOffset === value) {
  15168. return;
  15169. }
  15170. this._blurBoxOffset = value;
  15171. if (this._boxBlurPostprocess) {
  15172. this._boxBlurPostprocess.dispose();
  15173. }
  15174. var textureType;
  15175. var caps = this._scene.getEngine().getCaps();
  15176. if (this._useFullFloat) {
  15177. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  15178. }
  15179. else {
  15180. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  15181. }
  15182. 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);
  15183. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  15184. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  15185. });
  15186. },
  15187. enumerable: true,
  15188. configurable: true
  15189. });
  15190. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  15191. get: function () {
  15192. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  15193. },
  15194. set: function (value) {
  15195. this._depthScale = value;
  15196. },
  15197. enumerable: true,
  15198. configurable: true
  15199. });
  15200. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  15201. get: function () {
  15202. return this._filter;
  15203. },
  15204. set: function (value) {
  15205. if (this._filter === value) {
  15206. return;
  15207. }
  15208. this._filter = value;
  15209. if (this.usePoissonSampling || this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  15210. this._shadowMap.anisotropicFilteringLevel = 16;
  15211. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  15212. }
  15213. else {
  15214. this._shadowMap.anisotropicFilteringLevel = 1;
  15215. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  15216. }
  15217. this._light._markMeshesAsLightDirty();
  15218. },
  15219. enumerable: true,
  15220. configurable: true
  15221. });
  15222. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  15223. get: function () {
  15224. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  15225. return this.useExponentialShadowMap;
  15226. },
  15227. set: function (value) {
  15228. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  15229. this.useExponentialShadowMap = value;
  15230. },
  15231. enumerable: true,
  15232. configurable: true
  15233. });
  15234. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  15235. get: function () {
  15236. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  15237. },
  15238. set: function (value) {
  15239. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  15240. },
  15241. enumerable: true,
  15242. configurable: true
  15243. });
  15244. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  15245. get: function () {
  15246. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  15247. },
  15248. set: function (value) {
  15249. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  15250. },
  15251. enumerable: true,
  15252. configurable: true
  15253. });
  15254. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  15255. get: function () {
  15256. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  15257. return this.useBlurExponentialShadowMap;
  15258. },
  15259. set: function (value) {
  15260. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  15261. this.useBlurExponentialShadowMap = value;
  15262. },
  15263. enumerable: true,
  15264. configurable: true
  15265. });
  15266. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  15267. get: function () {
  15268. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  15269. },
  15270. set: function (value) {
  15271. if (this._light.needCube() && value) {
  15272. this.useExponentialShadowMap = true; // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  15273. }
  15274. else {
  15275. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  15276. }
  15277. },
  15278. enumerable: true,
  15279. configurable: true
  15280. });
  15281. /**
  15282. * Boolean : true when the ShadowGenerator is finally computed.
  15283. */
  15284. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  15285. var defines = [];
  15286. if (this._useFullFloat) {
  15287. defines.push("#define FULLFLOAT");
  15288. }
  15289. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  15290. defines.push("#define ESM");
  15291. }
  15292. if (this.getLight().needCube()) {
  15293. defines.push("#define CUBEMAP");
  15294. }
  15295. var attribs = [BABYLON.VertexBuffer.PositionKind];
  15296. var mesh = subMesh.getMesh();
  15297. var material = subMesh.getMaterial();
  15298. // Alpha test
  15299. if (material && material.needAlphaTesting()) {
  15300. defines.push("#define ALPHATEST");
  15301. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15302. attribs.push(BABYLON.VertexBuffer.UVKind);
  15303. defines.push("#define UV1");
  15304. }
  15305. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15306. var alphaTexture = material.getAlphaTestTexture();
  15307. if (alphaTexture.coordinatesIndex === 1) {
  15308. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  15309. defines.push("#define UV2");
  15310. }
  15311. }
  15312. }
  15313. // Bones
  15314. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  15315. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15316. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15317. if (mesh.numBoneInfluencers > 4) {
  15318. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  15319. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  15320. }
  15321. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  15322. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  15323. }
  15324. else {
  15325. defines.push("#define NUM_BONE_INFLUENCERS 0");
  15326. }
  15327. // Instances
  15328. if (useInstances) {
  15329. defines.push("#define INSTANCES");
  15330. attribs.push("world0");
  15331. attribs.push("world1");
  15332. attribs.push("world2");
  15333. attribs.push("world3");
  15334. }
  15335. // Get correct effect
  15336. var join = defines.join("\n");
  15337. if (this._cachedDefines !== join) {
  15338. this._cachedDefines = join;
  15339. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  15340. }
  15341. return this._effect.isReady();
  15342. };
  15343. /**
  15344. * Returns a RenderTargetTexture object : the shadow map texture.
  15345. */
  15346. ShadowGenerator.prototype.getShadowMap = function () {
  15347. return this._shadowMap;
  15348. };
  15349. /**
  15350. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  15351. */
  15352. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  15353. if (this._shadowMap2) {
  15354. return this._shadowMap2;
  15355. }
  15356. return this._shadowMap;
  15357. };
  15358. /**
  15359. * Returns the associated light object.
  15360. */
  15361. ShadowGenerator.prototype.getLight = function () {
  15362. return this._light;
  15363. };
  15364. // Methods
  15365. /**
  15366. * Returns a Matrix object : the updated transformation matrix.
  15367. */
  15368. ShadowGenerator.prototype.getTransformMatrix = function () {
  15369. var scene = this._scene;
  15370. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  15371. return this._transformMatrix;
  15372. }
  15373. this._currentRenderID = scene.getRenderId();
  15374. this._currentFaceIndexCache = this._currentFaceIndex;
  15375. var lightPosition = this._light.position;
  15376. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  15377. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  15378. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  15379. }
  15380. if (this._light.computeTransformedPosition()) {
  15381. lightPosition = this._light.transformedPosition;
  15382. }
  15383. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  15384. this._cachedPosition = lightPosition.clone();
  15385. this._cachedDirection = this._lightDirection.clone();
  15386. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  15387. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  15388. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15389. }
  15390. return this._transformMatrix;
  15391. };
  15392. /**
  15393. * Returns the darkness value (float).
  15394. */
  15395. ShadowGenerator.prototype.getDarkness = function () {
  15396. return this._darkness;
  15397. };
  15398. /**
  15399. * Sets the ShadowGenerator darkness value (float <= 1.0).
  15400. * Returns the ShadowGenerator.
  15401. */
  15402. ShadowGenerator.prototype.setDarkness = function (darkness) {
  15403. if (darkness >= 1.0)
  15404. this._darkness = 1.0;
  15405. else if (darkness <= 0.0)
  15406. this._darkness = 0.0;
  15407. else
  15408. this._darkness = darkness;
  15409. return this;
  15410. };
  15411. /**
  15412. * Sets the ability to have transparent shadow (boolean).
  15413. * Returns the ShadowGenerator.
  15414. */
  15415. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  15416. this._transparencyShadow = hasShadow;
  15417. return this;
  15418. };
  15419. ShadowGenerator.prototype._packHalf = function (depth) {
  15420. var scale = depth * 255.0;
  15421. var fract = scale - Math.floor(scale);
  15422. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  15423. };
  15424. /**
  15425. * Disposes the ShadowGenerator.
  15426. * Returns nothing.
  15427. */
  15428. ShadowGenerator.prototype.dispose = function () {
  15429. this._shadowMap.dispose();
  15430. if (this._shadowMap2) {
  15431. this._shadowMap2.dispose();
  15432. }
  15433. if (this._downSamplePostprocess) {
  15434. this._downSamplePostprocess.dispose();
  15435. }
  15436. if (this._boxBlurPostprocess) {
  15437. this._boxBlurPostprocess.dispose();
  15438. }
  15439. this._light._shadowGenerator = null;
  15440. this._light._markMeshesAsLightDirty();
  15441. };
  15442. /**
  15443. * Serializes the ShadowGenerator and returns a serializationObject.
  15444. */
  15445. ShadowGenerator.prototype.serialize = function () {
  15446. var serializationObject = {};
  15447. serializationObject.lightId = this._light.id;
  15448. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  15449. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  15450. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  15451. serializationObject.usePoissonSampling = this.usePoissonSampling;
  15452. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  15453. serializationObject.depthScale = this.depthScale;
  15454. serializationObject.darkness = this.getDarkness();
  15455. serializationObject.renderList = [];
  15456. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  15457. var mesh = this.getShadowMap().renderList[meshIndex];
  15458. serializationObject.renderList.push(mesh.id);
  15459. }
  15460. return serializationObject;
  15461. };
  15462. /**
  15463. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  15464. */
  15465. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  15466. //casting to point light, as light is missing the position attr and typescript complains.
  15467. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  15468. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  15469. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  15470. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  15471. meshes.forEach(function (mesh) {
  15472. shadowGenerator.getShadowMap().renderList.push(mesh);
  15473. });
  15474. }
  15475. if (parsedShadowGenerator.usePoissonSampling) {
  15476. shadowGenerator.usePoissonSampling = true;
  15477. }
  15478. else if (parsedShadowGenerator.useExponentialShadowMap) {
  15479. shadowGenerator.useExponentialShadowMap = true;
  15480. }
  15481. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  15482. shadowGenerator.useBlurExponentialShadowMap = true;
  15483. }
  15484. else if (parsedShadowGenerator.useVarianceShadowMap) {
  15485. shadowGenerator.useExponentialShadowMap = true;
  15486. }
  15487. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  15488. shadowGenerator.useBlurExponentialShadowMap = true;
  15489. }
  15490. if (parsedShadowGenerator.depthScale) {
  15491. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  15492. }
  15493. if (parsedShadowGenerator.blurScale) {
  15494. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  15495. }
  15496. if (parsedShadowGenerator.blurBoxOffset) {
  15497. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  15498. }
  15499. if (parsedShadowGenerator.bias !== undefined) {
  15500. shadowGenerator.bias = parsedShadowGenerator.bias;
  15501. }
  15502. if (parsedShadowGenerator.darkness) {
  15503. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  15504. }
  15505. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  15506. return shadowGenerator;
  15507. };
  15508. return ShadowGenerator;
  15509. }());
  15510. ShadowGenerator._FILTER_NONE = 0;
  15511. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  15512. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  15513. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  15514. BABYLON.ShadowGenerator = ShadowGenerator;
  15515. })(BABYLON || (BABYLON = {}));
  15516. //# sourceMappingURL=babylon.shadowGenerator.js.map
  15517. var BABYLON;
  15518. (function (BABYLON) {
  15519. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  15520. if (boxMin.x > sphereCenter.x + sphereRadius)
  15521. return false;
  15522. if (sphereCenter.x - sphereRadius > boxMax.x)
  15523. return false;
  15524. if (boxMin.y > sphereCenter.y + sphereRadius)
  15525. return false;
  15526. if (sphereCenter.y - sphereRadius > boxMax.y)
  15527. return false;
  15528. if (boxMin.z > sphereCenter.z + sphereRadius)
  15529. return false;
  15530. if (sphereCenter.z - sphereRadius > boxMax.z)
  15531. return false;
  15532. return true;
  15533. };
  15534. var getLowestRoot = (function () {
  15535. var result = { root: 0, found: false };
  15536. return function (a, b, c, maxR) {
  15537. result.root = 0;
  15538. result.found = false;
  15539. var determinant = b * b - 4.0 * a * c;
  15540. if (determinant < 0)
  15541. return result;
  15542. var sqrtD = Math.sqrt(determinant);
  15543. var r1 = (-b - sqrtD) / (2.0 * a);
  15544. var r2 = (-b + sqrtD) / (2.0 * a);
  15545. if (r1 > r2) {
  15546. var temp = r2;
  15547. r2 = r1;
  15548. r1 = temp;
  15549. }
  15550. if (r1 > 0 && r1 < maxR) {
  15551. result.root = r1;
  15552. result.found = true;
  15553. return result;
  15554. }
  15555. if (r2 > 0 && r2 < maxR) {
  15556. result.root = r2;
  15557. result.found = true;
  15558. return result;
  15559. }
  15560. return result;
  15561. };
  15562. })();
  15563. var Collider = (function () {
  15564. function Collider() {
  15565. this.radius = new BABYLON.Vector3(1, 1, 1);
  15566. this.retry = 0;
  15567. this.basePointWorld = BABYLON.Vector3.Zero();
  15568. this.velocityWorld = BABYLON.Vector3.Zero();
  15569. this.normalizedVelocity = BABYLON.Vector3.Zero();
  15570. this._collisionPoint = BABYLON.Vector3.Zero();
  15571. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  15572. this._tempVector = BABYLON.Vector3.Zero();
  15573. this._tempVector2 = BABYLON.Vector3.Zero();
  15574. this._tempVector3 = BABYLON.Vector3.Zero();
  15575. this._tempVector4 = BABYLON.Vector3.Zero();
  15576. this._edge = BABYLON.Vector3.Zero();
  15577. this._baseToVertex = BABYLON.Vector3.Zero();
  15578. this._destinationPoint = BABYLON.Vector3.Zero();
  15579. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  15580. this._displacementVector = BABYLON.Vector3.Zero();
  15581. this._collisionMask = -1;
  15582. }
  15583. Object.defineProperty(Collider.prototype, "collisionMask", {
  15584. get: function () {
  15585. return this._collisionMask;
  15586. },
  15587. set: function (mask) {
  15588. this._collisionMask = !isNaN(mask) ? mask : -1;
  15589. },
  15590. enumerable: true,
  15591. configurable: true
  15592. });
  15593. // Methods
  15594. Collider.prototype._initialize = function (source, dir, e) {
  15595. this.velocity = dir;
  15596. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  15597. this.basePoint = source;
  15598. source.multiplyToRef(this.radius, this.basePointWorld);
  15599. dir.multiplyToRef(this.radius, this.velocityWorld);
  15600. this.velocityWorldLength = this.velocityWorld.length();
  15601. this.epsilon = e;
  15602. this.collisionFound = false;
  15603. };
  15604. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  15605. pa.subtractToRef(point, this._tempVector);
  15606. pb.subtractToRef(point, this._tempVector2);
  15607. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  15608. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15609. if (d < 0)
  15610. return false;
  15611. pc.subtractToRef(point, this._tempVector3);
  15612. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  15613. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15614. if (d < 0)
  15615. return false;
  15616. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  15617. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15618. return d >= 0;
  15619. };
  15620. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  15621. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  15622. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  15623. if (distance > this.velocityWorldLength + max + sphereRadius) {
  15624. return false;
  15625. }
  15626. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  15627. return false;
  15628. return true;
  15629. };
  15630. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  15631. var t0;
  15632. var embeddedInPlane = false;
  15633. //defensive programming, actually not needed.
  15634. if (!trianglePlaneArray) {
  15635. trianglePlaneArray = [];
  15636. }
  15637. if (!trianglePlaneArray[faceIndex]) {
  15638. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  15639. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  15640. }
  15641. var trianglePlane = trianglePlaneArray[faceIndex];
  15642. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  15643. return;
  15644. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  15645. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  15646. if (normalDotVelocity == 0) {
  15647. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  15648. return;
  15649. embeddedInPlane = true;
  15650. t0 = 0;
  15651. }
  15652. else {
  15653. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15654. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15655. if (t0 > t1) {
  15656. var temp = t1;
  15657. t1 = t0;
  15658. t0 = temp;
  15659. }
  15660. if (t0 > 1.0 || t1 < 0.0)
  15661. return;
  15662. if (t0 < 0)
  15663. t0 = 0;
  15664. if (t0 > 1.0)
  15665. t0 = 1.0;
  15666. }
  15667. this._collisionPoint.copyFromFloats(0, 0, 0);
  15668. var found = false;
  15669. var t = 1.0;
  15670. if (!embeddedInPlane) {
  15671. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  15672. this.velocity.scaleToRef(t0, this._tempVector);
  15673. this._planeIntersectionPoint.addInPlace(this._tempVector);
  15674. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  15675. found = true;
  15676. t = t0;
  15677. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  15678. }
  15679. }
  15680. if (!found) {
  15681. var velocitySquaredLength = this.velocity.lengthSquared();
  15682. var a = velocitySquaredLength;
  15683. this.basePoint.subtractToRef(p1, this._tempVector);
  15684. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15685. var c = this._tempVector.lengthSquared() - 1.0;
  15686. var lowestRoot = getLowestRoot(a, b, c, t);
  15687. if (lowestRoot.found) {
  15688. t = lowestRoot.root;
  15689. found = true;
  15690. this._collisionPoint.copyFrom(p1);
  15691. }
  15692. this.basePoint.subtractToRef(p2, this._tempVector);
  15693. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15694. c = this._tempVector.lengthSquared() - 1.0;
  15695. lowestRoot = getLowestRoot(a, b, c, t);
  15696. if (lowestRoot.found) {
  15697. t = lowestRoot.root;
  15698. found = true;
  15699. this._collisionPoint.copyFrom(p2);
  15700. }
  15701. this.basePoint.subtractToRef(p3, this._tempVector);
  15702. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15703. c = this._tempVector.lengthSquared() - 1.0;
  15704. lowestRoot = getLowestRoot(a, b, c, t);
  15705. if (lowestRoot.found) {
  15706. t = lowestRoot.root;
  15707. found = true;
  15708. this._collisionPoint.copyFrom(p3);
  15709. }
  15710. p2.subtractToRef(p1, this._edge);
  15711. p1.subtractToRef(this.basePoint, this._baseToVertex);
  15712. var edgeSquaredLength = this._edge.lengthSquared();
  15713. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15714. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15715. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15716. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15717. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15718. lowestRoot = getLowestRoot(a, b, c, t);
  15719. if (lowestRoot.found) {
  15720. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15721. if (f >= 0.0 && f <= 1.0) {
  15722. t = lowestRoot.root;
  15723. found = true;
  15724. this._edge.scaleInPlace(f);
  15725. p1.addToRef(this._edge, this._collisionPoint);
  15726. }
  15727. }
  15728. p3.subtractToRef(p2, this._edge);
  15729. p2.subtractToRef(this.basePoint, this._baseToVertex);
  15730. edgeSquaredLength = this._edge.lengthSquared();
  15731. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15732. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15733. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15734. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15735. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15736. lowestRoot = getLowestRoot(a, b, c, t);
  15737. if (lowestRoot.found) {
  15738. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15739. if (f >= 0.0 && f <= 1.0) {
  15740. t = lowestRoot.root;
  15741. found = true;
  15742. this._edge.scaleInPlace(f);
  15743. p2.addToRef(this._edge, this._collisionPoint);
  15744. }
  15745. }
  15746. p1.subtractToRef(p3, this._edge);
  15747. p3.subtractToRef(this.basePoint, this._baseToVertex);
  15748. edgeSquaredLength = this._edge.lengthSquared();
  15749. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15750. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15751. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15752. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15753. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15754. lowestRoot = getLowestRoot(a, b, c, t);
  15755. if (lowestRoot.found) {
  15756. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15757. if (f >= 0.0 && f <= 1.0) {
  15758. t = lowestRoot.root;
  15759. found = true;
  15760. this._edge.scaleInPlace(f);
  15761. p3.addToRef(this._edge, this._collisionPoint);
  15762. }
  15763. }
  15764. }
  15765. if (found) {
  15766. var distToCollision = t * this.velocity.length();
  15767. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  15768. if (!this.intersectionPoint) {
  15769. this.intersectionPoint = this._collisionPoint.clone();
  15770. }
  15771. else {
  15772. this.intersectionPoint.copyFrom(this._collisionPoint);
  15773. }
  15774. this.nearestDistance = distToCollision;
  15775. this.collisionFound = true;
  15776. }
  15777. }
  15778. };
  15779. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  15780. for (var i = indexStart; i < indexEnd; i += 3) {
  15781. var p1 = pts[indices[i] - decal];
  15782. var p2 = pts[indices[i + 1] - decal];
  15783. var p3 = pts[indices[i + 2] - decal];
  15784. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  15785. }
  15786. };
  15787. Collider.prototype._getResponse = function (pos, vel) {
  15788. pos.addToRef(vel, this._destinationPoint);
  15789. vel.scaleInPlace((this.nearestDistance / vel.length()));
  15790. this.basePoint.addToRef(vel, pos);
  15791. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  15792. this._slidePlaneNormal.normalize();
  15793. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  15794. pos.addInPlace(this._displacementVector);
  15795. this.intersectionPoint.addInPlace(this._displacementVector);
  15796. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  15797. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  15798. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  15799. };
  15800. return Collider;
  15801. }());
  15802. BABYLON.Collider = Collider;
  15803. })(BABYLON || (BABYLON = {}));
  15804. //# sourceMappingURL=babylon.collider.js.map
  15805. var BABYLON;
  15806. (function (BABYLON) {
  15807. //WebWorker code will be inserted to this variable.
  15808. BABYLON.CollisionWorker = "";
  15809. var WorkerTaskType;
  15810. (function (WorkerTaskType) {
  15811. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  15812. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  15813. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  15814. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  15815. var WorkerReplyType;
  15816. (function (WorkerReplyType) {
  15817. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  15818. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  15819. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  15820. var CollisionCoordinatorWorker = (function () {
  15821. function CollisionCoordinatorWorker() {
  15822. var _this = this;
  15823. this._scaledPosition = BABYLON.Vector3.Zero();
  15824. this._scaledVelocity = BABYLON.Vector3.Zero();
  15825. this.onMeshUpdated = function (mesh) {
  15826. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  15827. };
  15828. this.onGeometryUpdated = function (geometry) {
  15829. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  15830. };
  15831. this._afterRender = function () {
  15832. if (!_this._init)
  15833. return;
  15834. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  15835. return;
  15836. }
  15837. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  15838. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  15839. if (_this._runningUpdated > 4) {
  15840. return;
  15841. }
  15842. ++_this._runningUpdated;
  15843. var payload = {
  15844. updatedMeshes: _this._addUpdateMeshesList,
  15845. updatedGeometries: _this._addUpdateGeometriesList,
  15846. removedGeometries: _this._toRemoveGeometryArray,
  15847. removedMeshes: _this._toRemoveMeshesArray
  15848. };
  15849. var message = {
  15850. payload: payload,
  15851. taskType: WorkerTaskType.UPDATE
  15852. };
  15853. var serializable = [];
  15854. for (var id in payload.updatedGeometries) {
  15855. if (payload.updatedGeometries.hasOwnProperty(id)) {
  15856. //prepare transferables
  15857. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  15858. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  15859. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  15860. }
  15861. }
  15862. _this._worker.postMessage(message, serializable);
  15863. _this._addUpdateMeshesList = {};
  15864. _this._addUpdateGeometriesList = {};
  15865. _this._toRemoveGeometryArray = [];
  15866. _this._toRemoveMeshesArray = [];
  15867. };
  15868. this._onMessageFromWorker = function (e) {
  15869. var returnData = e.data;
  15870. if (returnData.error != WorkerReplyType.SUCCESS) {
  15871. //TODO what errors can be returned from the worker?
  15872. BABYLON.Tools.Warn("error returned from worker!");
  15873. return;
  15874. }
  15875. switch (returnData.taskType) {
  15876. case WorkerTaskType.INIT:
  15877. _this._init = true;
  15878. //Update the worked with ALL of the scene's current state
  15879. _this._scene.meshes.forEach(function (mesh) {
  15880. _this.onMeshAdded(mesh);
  15881. });
  15882. _this._scene.getGeometries().forEach(function (geometry) {
  15883. _this.onGeometryAdded(geometry);
  15884. });
  15885. break;
  15886. case WorkerTaskType.UPDATE:
  15887. _this._runningUpdated--;
  15888. break;
  15889. case WorkerTaskType.COLLIDE:
  15890. _this._runningCollisionTask = false;
  15891. var returnPayload = returnData.payload;
  15892. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  15893. return;
  15894. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  15895. //cleanup
  15896. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  15897. break;
  15898. }
  15899. };
  15900. this._collisionsCallbackArray = [];
  15901. this._init = false;
  15902. this._runningUpdated = 0;
  15903. this._runningCollisionTask = false;
  15904. this._addUpdateMeshesList = {};
  15905. this._addUpdateGeometriesList = {};
  15906. this._toRemoveGeometryArray = [];
  15907. this._toRemoveMeshesArray = [];
  15908. }
  15909. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15910. if (!this._init)
  15911. return;
  15912. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  15913. return;
  15914. position.divideToRef(collider.radius, this._scaledPosition);
  15915. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15916. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  15917. var payload = {
  15918. collider: {
  15919. position: this._scaledPosition.asArray(),
  15920. velocity: this._scaledVelocity.asArray(),
  15921. radius: collider.radius.asArray()
  15922. },
  15923. collisionId: collisionIndex,
  15924. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  15925. maximumRetry: maximumRetry
  15926. };
  15927. var message = {
  15928. payload: payload,
  15929. taskType: WorkerTaskType.COLLIDE
  15930. };
  15931. this._worker.postMessage(message);
  15932. };
  15933. CollisionCoordinatorWorker.prototype.init = function (scene) {
  15934. this._scene = scene;
  15935. this._scene.registerAfterRender(this._afterRender);
  15936. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  15937. this._worker = new Worker(workerUrl);
  15938. this._worker.onmessage = this._onMessageFromWorker;
  15939. var message = {
  15940. payload: {},
  15941. taskType: WorkerTaskType.INIT
  15942. };
  15943. this._worker.postMessage(message);
  15944. };
  15945. CollisionCoordinatorWorker.prototype.destroy = function () {
  15946. this._scene.unregisterAfterRender(this._afterRender);
  15947. this._worker.terminate();
  15948. };
  15949. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  15950. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  15951. this.onMeshUpdated(mesh);
  15952. };
  15953. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  15954. this._toRemoveMeshesArray.push(mesh.uniqueId);
  15955. };
  15956. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  15957. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  15958. geometry.onGeometryUpdated = this.onGeometryUpdated;
  15959. this.onGeometryUpdated(geometry);
  15960. };
  15961. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  15962. this._toRemoveGeometryArray.push(geometry.id);
  15963. };
  15964. return CollisionCoordinatorWorker;
  15965. }());
  15966. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  15967. var submeshes = [];
  15968. if (mesh.subMeshes) {
  15969. submeshes = mesh.subMeshes.map(function (sm, idx) {
  15970. return {
  15971. position: idx,
  15972. verticesStart: sm.verticesStart,
  15973. verticesCount: sm.verticesCount,
  15974. indexStart: sm.indexStart,
  15975. indexCount: sm.indexCount,
  15976. hasMaterial: !!sm.getMaterial(),
  15977. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15978. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  15979. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15980. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  15981. };
  15982. });
  15983. }
  15984. var geometryId = null;
  15985. if (mesh instanceof BABYLON.Mesh) {
  15986. geometryId = mesh.geometry ? mesh.geometry.id : null;
  15987. }
  15988. else if (mesh instanceof BABYLON.InstancedMesh) {
  15989. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  15990. }
  15991. return {
  15992. uniqueId: mesh.uniqueId,
  15993. id: mesh.id,
  15994. name: mesh.name,
  15995. geometryId: geometryId,
  15996. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15997. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  15998. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15999. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  16000. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  16001. subMeshes: submeshes,
  16002. checkCollisions: mesh.checkCollisions
  16003. };
  16004. };
  16005. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  16006. return {
  16007. id: geometry.id,
  16008. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  16009. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  16010. indices: new Uint32Array(geometry.getIndices() || []),
  16011. };
  16012. };
  16013. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  16014. var CollisionCoordinatorLegacy = (function () {
  16015. function CollisionCoordinatorLegacy() {
  16016. this._scaledPosition = BABYLON.Vector3.Zero();
  16017. this._scaledVelocity = BABYLON.Vector3.Zero();
  16018. this._finalPosition = BABYLON.Vector3.Zero();
  16019. }
  16020. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  16021. position.divideToRef(collider.radius, this._scaledPosition);
  16022. velocity.divideToRef(collider.radius, this._scaledVelocity);
  16023. collider.collidedMesh = null;
  16024. collider.retry = 0;
  16025. collider.initialVelocity = this._scaledVelocity;
  16026. collider.initialPosition = this._scaledPosition;
  16027. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  16028. this._finalPosition.multiplyInPlace(collider.radius);
  16029. //run the callback
  16030. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  16031. };
  16032. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  16033. this._scene = scene;
  16034. };
  16035. CollisionCoordinatorLegacy.prototype.destroy = function () {
  16036. //Legacy need no destruction method.
  16037. };
  16038. //No update in legacy mode
  16039. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  16040. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  16041. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  16042. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  16043. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  16044. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  16045. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  16046. if (excludedMesh === void 0) { excludedMesh = null; }
  16047. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  16048. if (collider.retry >= maximumRetry) {
  16049. finalPosition.copyFrom(position);
  16050. return;
  16051. }
  16052. // Check if this is a mesh else camera or -1
  16053. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  16054. collider._initialize(position, velocity, closeDistance);
  16055. // Check all meshes
  16056. for (var index = 0; index < this._scene.meshes.length; index++) {
  16057. var mesh = this._scene.meshes[index];
  16058. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  16059. mesh._checkCollision(collider);
  16060. }
  16061. }
  16062. if (!collider.collisionFound) {
  16063. position.addToRef(velocity, finalPosition);
  16064. return;
  16065. }
  16066. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  16067. collider._getResponse(position, velocity);
  16068. }
  16069. if (velocity.length() <= closeDistance) {
  16070. finalPosition.copyFrom(position);
  16071. return;
  16072. }
  16073. collider.retry++;
  16074. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  16075. };
  16076. return CollisionCoordinatorLegacy;
  16077. }());
  16078. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  16079. })(BABYLON || (BABYLON = {}));
  16080. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  16081. var BABYLON;
  16082. (function (BABYLON) {
  16083. var Camera = (function (_super) {
  16084. __extends(Camera, _super);
  16085. function Camera(name, position, scene) {
  16086. var _this = _super.call(this, name, scene) || this;
  16087. _this.upVector = BABYLON.Vector3.Up();
  16088. _this.orthoLeft = null;
  16089. _this.orthoRight = null;
  16090. _this.orthoBottom = null;
  16091. _this.orthoTop = null;
  16092. _this.fov = 0.8;
  16093. _this.minZ = 1.0;
  16094. _this.maxZ = 10000.0;
  16095. _this.inertia = 0.9;
  16096. _this.mode = Camera.PERSPECTIVE_CAMERA;
  16097. _this.isIntermediate = false;
  16098. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  16099. _this.layerMask = 0x0FFFFFFF;
  16100. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  16101. // Camera rig members
  16102. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  16103. _this._rigCameras = new Array();
  16104. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  16105. // Cache
  16106. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  16107. _this._projectionMatrix = new BABYLON.Matrix();
  16108. _this._doNotComputeProjectionMatrix = false;
  16109. _this._postProcesses = new Array();
  16110. _this._transformMatrix = BABYLON.Matrix.Zero();
  16111. _this._activeMeshes = new BABYLON.SmartArray(256);
  16112. _this._globalPosition = BABYLON.Vector3.Zero();
  16113. _this._refreshFrustumPlanes = true;
  16114. _this.getScene().addCamera(_this);
  16115. if (!_this.getScene().activeCamera) {
  16116. _this.getScene().activeCamera = _this;
  16117. }
  16118. _this.position = position;
  16119. return _this;
  16120. }
  16121. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  16122. get: function () {
  16123. return Camera._PERSPECTIVE_CAMERA;
  16124. },
  16125. enumerable: true,
  16126. configurable: true
  16127. });
  16128. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  16129. get: function () {
  16130. return Camera._ORTHOGRAPHIC_CAMERA;
  16131. },
  16132. enumerable: true,
  16133. configurable: true
  16134. });
  16135. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  16136. get: function () {
  16137. return Camera._FOVMODE_VERTICAL_FIXED;
  16138. },
  16139. enumerable: true,
  16140. configurable: true
  16141. });
  16142. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  16143. get: function () {
  16144. return Camera._FOVMODE_HORIZONTAL_FIXED;
  16145. },
  16146. enumerable: true,
  16147. configurable: true
  16148. });
  16149. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  16150. get: function () {
  16151. return Camera._RIG_MODE_NONE;
  16152. },
  16153. enumerable: true,
  16154. configurable: true
  16155. });
  16156. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  16157. get: function () {
  16158. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  16159. },
  16160. enumerable: true,
  16161. configurable: true
  16162. });
  16163. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  16164. get: function () {
  16165. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  16166. },
  16167. enumerable: true,
  16168. configurable: true
  16169. });
  16170. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  16171. get: function () {
  16172. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16173. },
  16174. enumerable: true,
  16175. configurable: true
  16176. });
  16177. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  16178. get: function () {
  16179. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  16180. },
  16181. enumerable: true,
  16182. configurable: true
  16183. });
  16184. Object.defineProperty(Camera, "RIG_MODE_VR", {
  16185. get: function () {
  16186. return Camera._RIG_MODE_VR;
  16187. },
  16188. enumerable: true,
  16189. configurable: true
  16190. });
  16191. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  16192. get: function () {
  16193. return Camera._RIG_MODE_WEBVR;
  16194. },
  16195. enumerable: true,
  16196. configurable: true
  16197. });
  16198. Camera.prototype.getClassName = function () {
  16199. return "Camera";
  16200. };
  16201. /**
  16202. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16203. */
  16204. Camera.prototype.toString = function (fullDetails) {
  16205. var ret = "Name: " + this.name;
  16206. ret += ", type: " + this.getClassName();
  16207. if (this.animations) {
  16208. for (var i = 0; i < this.animations.length; i++) {
  16209. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16210. }
  16211. }
  16212. if (fullDetails) {
  16213. }
  16214. return ret;
  16215. };
  16216. Object.defineProperty(Camera.prototype, "globalPosition", {
  16217. get: function () {
  16218. return this._globalPosition;
  16219. },
  16220. enumerable: true,
  16221. configurable: true
  16222. });
  16223. Camera.prototype.getActiveMeshes = function () {
  16224. return this._activeMeshes;
  16225. };
  16226. Camera.prototype.isActiveMesh = function (mesh) {
  16227. return (this._activeMeshes.indexOf(mesh) !== -1);
  16228. };
  16229. //Cache
  16230. Camera.prototype._initCache = function () {
  16231. _super.prototype._initCache.call(this);
  16232. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16233. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16234. this._cache.mode = undefined;
  16235. this._cache.minZ = undefined;
  16236. this._cache.maxZ = undefined;
  16237. this._cache.fov = undefined;
  16238. this._cache.fovMode = undefined;
  16239. this._cache.aspectRatio = undefined;
  16240. this._cache.orthoLeft = undefined;
  16241. this._cache.orthoRight = undefined;
  16242. this._cache.orthoBottom = undefined;
  16243. this._cache.orthoTop = undefined;
  16244. this._cache.renderWidth = undefined;
  16245. this._cache.renderHeight = undefined;
  16246. };
  16247. Camera.prototype._updateCache = function (ignoreParentClass) {
  16248. if (!ignoreParentClass) {
  16249. _super.prototype._updateCache.call(this);
  16250. }
  16251. var engine = this.getEngine();
  16252. this._cache.position.copyFrom(this.position);
  16253. this._cache.upVector.copyFrom(this.upVector);
  16254. this._cache.mode = this.mode;
  16255. this._cache.minZ = this.minZ;
  16256. this._cache.maxZ = this.maxZ;
  16257. this._cache.fov = this.fov;
  16258. this._cache.fovMode = this.fovMode;
  16259. this._cache.aspectRatio = engine.getAspectRatio(this);
  16260. this._cache.orthoLeft = this.orthoLeft;
  16261. this._cache.orthoRight = this.orthoRight;
  16262. this._cache.orthoBottom = this.orthoBottom;
  16263. this._cache.orthoTop = this.orthoTop;
  16264. this._cache.renderWidth = engine.getRenderWidth();
  16265. this._cache.renderHeight = engine.getRenderHeight();
  16266. };
  16267. Camera.prototype._updateFromScene = function () {
  16268. this.updateCache();
  16269. this.update();
  16270. };
  16271. // Synchronized
  16272. Camera.prototype._isSynchronized = function () {
  16273. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16274. };
  16275. Camera.prototype._isSynchronizedViewMatrix = function () {
  16276. if (!_super.prototype._isSynchronized.call(this))
  16277. return false;
  16278. return this._cache.position.equals(this.position)
  16279. && this._cache.upVector.equals(this.upVector)
  16280. && this.isSynchronizedWithParent();
  16281. };
  16282. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16283. var check = this._cache.mode === this.mode
  16284. && this._cache.minZ === this.minZ
  16285. && this._cache.maxZ === this.maxZ;
  16286. if (!check) {
  16287. return false;
  16288. }
  16289. var engine = this.getEngine();
  16290. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16291. check = this._cache.fov === this.fov
  16292. && this._cache.fovMode === this.fovMode
  16293. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16294. }
  16295. else {
  16296. check = this._cache.orthoLeft === this.orthoLeft
  16297. && this._cache.orthoRight === this.orthoRight
  16298. && this._cache.orthoBottom === this.orthoBottom
  16299. && this._cache.orthoTop === this.orthoTop
  16300. && this._cache.renderWidth === engine.getRenderWidth()
  16301. && this._cache.renderHeight === engine.getRenderHeight();
  16302. }
  16303. return check;
  16304. };
  16305. // Controls
  16306. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16307. };
  16308. Camera.prototype.detachControl = function (element) {
  16309. };
  16310. Camera.prototype.update = function () {
  16311. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16312. this._updateRigCameras();
  16313. }
  16314. this._checkInputs();
  16315. };
  16316. Camera.prototype._checkInputs = function () {
  16317. };
  16318. Object.defineProperty(Camera.prototype, "rigCameras", {
  16319. get: function () {
  16320. return this._rigCameras;
  16321. },
  16322. enumerable: true,
  16323. configurable: true
  16324. });
  16325. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16326. get: function () {
  16327. return this._rigPostProcess;
  16328. },
  16329. enumerable: true,
  16330. configurable: true
  16331. });
  16332. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16333. // invalidate framebuffer
  16334. if (this._postProcesses.length > 0) {
  16335. this._postProcesses[0].markTextureDirty();
  16336. }
  16337. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16338. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16339. var cam = this._rigCameras[i];
  16340. var rigPostProcess = cam._rigPostProcess;
  16341. // for VR rig, there does not have to be a post process
  16342. if (rigPostProcess) {
  16343. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16344. if (isPass) {
  16345. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16346. cam.isIntermediate = this._postProcesses.length === 0;
  16347. }
  16348. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16349. rigPostProcess.markTextureDirty();
  16350. }
  16351. else {
  16352. cam._postProcesses = this._postProcesses.slice(0);
  16353. }
  16354. }
  16355. };
  16356. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16357. if (insertAt === void 0) { insertAt = null; }
  16358. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16359. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16360. return 0;
  16361. }
  16362. if (insertAt == null || insertAt < 0) {
  16363. this._postProcesses.push(postProcess);
  16364. }
  16365. else {
  16366. this._postProcesses.splice(insertAt, 0, postProcess);
  16367. }
  16368. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16369. return this._postProcesses.indexOf(postProcess);
  16370. };
  16371. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  16372. if (atIndices === void 0) { atIndices = null; }
  16373. var result = [];
  16374. var i;
  16375. var index;
  16376. if (!atIndices) {
  16377. var idx = this._postProcesses.indexOf(postProcess);
  16378. if (idx !== -1) {
  16379. this._postProcesses.splice(idx, 1);
  16380. }
  16381. }
  16382. else {
  16383. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  16384. // iterate descending, so can just splice as we go
  16385. for (i = atIndices.length - 1; i >= 0; i--) {
  16386. if (this._postProcesses[atIndices[i]] !== postProcess) {
  16387. result.push(i);
  16388. continue;
  16389. }
  16390. index = atIndices[i];
  16391. this._postProcesses.splice(index, 1);
  16392. }
  16393. }
  16394. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16395. return result;
  16396. };
  16397. Camera.prototype.getWorldMatrix = function () {
  16398. if (!this._worldMatrix) {
  16399. this._worldMatrix = BABYLON.Matrix.Identity();
  16400. }
  16401. var viewMatrix = this.getViewMatrix();
  16402. viewMatrix.invertToRef(this._worldMatrix);
  16403. return this._worldMatrix;
  16404. };
  16405. Camera.prototype._getViewMatrix = function () {
  16406. return BABYLON.Matrix.Identity();
  16407. };
  16408. Camera.prototype.getViewMatrix = function (force) {
  16409. this._computedViewMatrix = this._computeViewMatrix(force);
  16410. if (!force && this._isSynchronizedViewMatrix()) {
  16411. return this._computedViewMatrix;
  16412. }
  16413. this._refreshFrustumPlanes = true;
  16414. if (!this.parent || !this.parent.getWorldMatrix) {
  16415. this._globalPosition.copyFrom(this.position);
  16416. }
  16417. else {
  16418. if (!this._worldMatrix) {
  16419. this._worldMatrix = BABYLON.Matrix.Identity();
  16420. }
  16421. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16422. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16423. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16424. this._computedViewMatrix.invert();
  16425. this._markSyncedWithParent();
  16426. }
  16427. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16428. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16429. }
  16430. this._currentRenderId = this.getScene().getRenderId();
  16431. return this._computedViewMatrix;
  16432. };
  16433. Camera.prototype._computeViewMatrix = function (force) {
  16434. if (!force && this._isSynchronizedViewMatrix()) {
  16435. return this._computedViewMatrix;
  16436. }
  16437. this._computedViewMatrix = this._getViewMatrix();
  16438. this._currentRenderId = this.getScene().getRenderId();
  16439. return this._computedViewMatrix;
  16440. };
  16441. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16442. this._doNotComputeProjectionMatrix = true;
  16443. if (projection !== undefined) {
  16444. this._projectionMatrix = projection;
  16445. }
  16446. };
  16447. ;
  16448. Camera.prototype.unfreezeProjectionMatrix = function () {
  16449. this._doNotComputeProjectionMatrix = false;
  16450. };
  16451. ;
  16452. Camera.prototype.getProjectionMatrix = function (force) {
  16453. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16454. return this._projectionMatrix;
  16455. }
  16456. this._refreshFrustumPlanes = true;
  16457. var engine = this.getEngine();
  16458. var scene = this.getScene();
  16459. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16460. if (this.minZ <= 0) {
  16461. this.minZ = 0.1;
  16462. }
  16463. if (scene.useRightHandedSystem) {
  16464. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16465. }
  16466. else {
  16467. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16468. }
  16469. return this._projectionMatrix;
  16470. }
  16471. var halfWidth = engine.getRenderWidth() / 2.0;
  16472. var halfHeight = engine.getRenderHeight() / 2.0;
  16473. if (scene.useRightHandedSystem) {
  16474. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16475. }
  16476. else {
  16477. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16478. }
  16479. return this._projectionMatrix;
  16480. };
  16481. Camera.prototype.getTranformationMatrix = function () {
  16482. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16483. return this._transformMatrix;
  16484. };
  16485. Camera.prototype.updateFrustumPlanes = function () {
  16486. if (!this._refreshFrustumPlanes) {
  16487. return;
  16488. }
  16489. this.getTranformationMatrix();
  16490. if (!this._frustumPlanes) {
  16491. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16492. }
  16493. else {
  16494. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16495. }
  16496. this._refreshFrustumPlanes = false;
  16497. };
  16498. Camera.prototype.isInFrustum = function (target) {
  16499. this.updateFrustumPlanes();
  16500. return target.isInFrustum(this._frustumPlanes);
  16501. };
  16502. Camera.prototype.isCompletelyInFrustum = function (target) {
  16503. this.updateFrustumPlanes();
  16504. return target.isCompletelyInFrustum(this._frustumPlanes);
  16505. };
  16506. Camera.prototype.dispose = function () {
  16507. // Animations
  16508. this.getScene().stopAnimation(this);
  16509. // Remove from scene
  16510. this.getScene().removeCamera(this);
  16511. while (this._rigCameras.length > 0) {
  16512. this._rigCameras.pop().dispose();
  16513. }
  16514. // Postprocesses
  16515. var i = this._postProcesses.length;
  16516. while (--i >= 0) {
  16517. this._postProcesses[i].dispose(this);
  16518. }
  16519. _super.prototype.dispose.call(this);
  16520. };
  16521. // ---- Camera rigs section ----
  16522. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16523. while (this._rigCameras.length > 0) {
  16524. this._rigCameras.pop().dispose();
  16525. }
  16526. this.cameraRigMode = mode;
  16527. this._cameraRigParams = {};
  16528. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16529. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16530. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16531. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16532. // create the rig cameras, unless none
  16533. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16534. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  16535. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  16536. }
  16537. switch (this.cameraRigMode) {
  16538. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16539. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16540. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16541. break;
  16542. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16543. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16544. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16545. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16546. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16547. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16548. break;
  16549. case Camera.RIG_MODE_VR:
  16550. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16551. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16552. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16553. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16554. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16555. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16556. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16557. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16558. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16559. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16560. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16561. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16562. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16563. if (metrics.compensateDistortion) {
  16564. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16565. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16566. }
  16567. break;
  16568. case Camera.RIG_MODE_WEBVR:
  16569. if (rigParams.vrDisplay) {
  16570. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16571. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16572. //Left eye
  16573. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16574. this._rigCameras[0].setCameraRigParameter("left", true);
  16575. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16576. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16577. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16578. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16579. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16580. this._rigCameras[0].parent = this;
  16581. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16582. //Right eye
  16583. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16584. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16585. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16586. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16587. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16588. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16589. this._rigCameras[1].parent = this;
  16590. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16591. }
  16592. break;
  16593. }
  16594. this._cascadePostProcessesToRigCams();
  16595. this.
  16596. update();
  16597. };
  16598. Camera.prototype._getVRProjectionMatrix = function () {
  16599. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16600. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16601. return this._projectionMatrix;
  16602. };
  16603. Camera.prototype._updateCameraRotationMatrix = function () {
  16604. //Here for WebVR
  16605. };
  16606. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16607. //Here for WebVR
  16608. };
  16609. /**
  16610. * This function MUST be overwritten by the different WebVR cameras available.
  16611. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16612. */
  16613. Camera.prototype._getWebVRProjectionMatrix = function () {
  16614. return BABYLON.Matrix.Identity();
  16615. };
  16616. /**
  16617. * This function MUST be overwritten by the different WebVR cameras available.
  16618. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16619. */
  16620. Camera.prototype._getWebVRViewMatrix = function () {
  16621. return BABYLON.Matrix.Identity();
  16622. };
  16623. Camera.prototype.setCameraRigParameter = function (name, value) {
  16624. if (!this._cameraRigParams) {
  16625. this._cameraRigParams = {};
  16626. }
  16627. this._cameraRigParams[name] = value;
  16628. //provisionnally:
  16629. if (name === "interaxialDistance") {
  16630. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16631. }
  16632. };
  16633. /**
  16634. * needs to be overridden by children so sub has required properties to be copied
  16635. */
  16636. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16637. return null;
  16638. };
  16639. /**
  16640. * May need to be overridden by children
  16641. */
  16642. Camera.prototype._updateRigCameras = function () {
  16643. for (var i = 0; i < this._rigCameras.length; i++) {
  16644. this._rigCameras[i].minZ = this.minZ;
  16645. this._rigCameras[i].maxZ = this.maxZ;
  16646. this._rigCameras[i].fov = this.fov;
  16647. }
  16648. // only update viewport when ANAGLYPH
  16649. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16650. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16651. }
  16652. };
  16653. Camera.prototype._setupInputs = function () {
  16654. };
  16655. Camera.prototype.serialize = function () {
  16656. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16657. // Type
  16658. serializationObject.type = this.getClassName();
  16659. // Parent
  16660. if (this.parent) {
  16661. serializationObject.parentId = this.parent.id;
  16662. }
  16663. if (this.inputs) {
  16664. this.inputs.serialize(serializationObject);
  16665. }
  16666. // Animations
  16667. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16668. serializationObject.ranges = this.serializeAnimationRanges();
  16669. return serializationObject;
  16670. };
  16671. Camera.prototype.clone = function (name) {
  16672. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16673. };
  16674. Camera.prototype.getDirection = function (localAxis) {
  16675. var result = BABYLON.Vector3.Zero();
  16676. this.getDirectionToRef(localAxis, result);
  16677. return result;
  16678. };
  16679. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16680. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16681. };
  16682. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16683. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16684. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16685. switch (type) {
  16686. case "ArcRotateCamera":
  16687. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16688. case "DeviceOrientationCamera":
  16689. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16690. case "FollowCamera":
  16691. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16692. case "ArcFollowCamera":
  16693. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16694. case "GamepadCamera":
  16695. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16696. case "TouchCamera":
  16697. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16698. case "VirtualJoysticksCamera":
  16699. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16700. case "WebVRFreeCamera":
  16701. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16702. case "WebVRGamepadCamera":
  16703. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16704. case "VRDeviceOrientationFreeCamera":
  16705. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16706. case "VRDeviceOrientationGamepadCamera":
  16707. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16708. case "AnaglyphArcRotateCamera":
  16709. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16710. case "AnaglyphFreeCamera":
  16711. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16712. case "AnaglyphGamepadCamera":
  16713. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16714. case "AnaglyphUniversalCamera":
  16715. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16716. case "StereoscopicArcRotateCamera":
  16717. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16718. case "StereoscopicFreeCamera":
  16719. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16720. case "StereoscopicGamepadCamera":
  16721. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16722. case "StereoscopicUniversalCamera":
  16723. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16724. case "FreeCamera":
  16725. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16726. default:
  16727. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16728. }
  16729. };
  16730. Camera.Parse = function (parsedCamera, scene) {
  16731. var type = parsedCamera.type;
  16732. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16733. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16734. // Parent
  16735. if (parsedCamera.parentId) {
  16736. camera._waitingParentId = parsedCamera.parentId;
  16737. }
  16738. //If camera has an input manager, let it parse inputs settings
  16739. if (camera.inputs) {
  16740. camera.inputs.parse(parsedCamera);
  16741. camera._setupInputs();
  16742. }
  16743. // Target
  16744. if (parsedCamera.target) {
  16745. if (camera.setTarget) {
  16746. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16747. }
  16748. }
  16749. // Apply 3d rig, when found
  16750. if (parsedCamera.cameraRigMode) {
  16751. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16752. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16753. }
  16754. // Animations
  16755. if (parsedCamera.animations) {
  16756. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16757. var parsedAnimation = parsedCamera.animations[animationIndex];
  16758. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16759. }
  16760. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16761. }
  16762. if (parsedCamera.autoAnimate) {
  16763. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16764. }
  16765. return camera;
  16766. };
  16767. return Camera;
  16768. }(BABYLON.Node));
  16769. // Statics
  16770. Camera._PERSPECTIVE_CAMERA = 0;
  16771. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16772. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16773. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16774. Camera._RIG_MODE_NONE = 0;
  16775. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16776. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16777. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16778. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16779. Camera._RIG_MODE_VR = 20;
  16780. Camera._RIG_MODE_WEBVR = 21;
  16781. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16782. __decorate([
  16783. BABYLON.serializeAsVector3()
  16784. ], Camera.prototype, "position", void 0);
  16785. __decorate([
  16786. BABYLON.serializeAsVector3()
  16787. ], Camera.prototype, "upVector", void 0);
  16788. __decorate([
  16789. BABYLON.serialize()
  16790. ], Camera.prototype, "orthoLeft", void 0);
  16791. __decorate([
  16792. BABYLON.serialize()
  16793. ], Camera.prototype, "orthoRight", void 0);
  16794. __decorate([
  16795. BABYLON.serialize()
  16796. ], Camera.prototype, "orthoBottom", void 0);
  16797. __decorate([
  16798. BABYLON.serialize()
  16799. ], Camera.prototype, "orthoTop", void 0);
  16800. __decorate([
  16801. BABYLON.serialize()
  16802. ], Camera.prototype, "fov", void 0);
  16803. __decorate([
  16804. BABYLON.serialize()
  16805. ], Camera.prototype, "minZ", void 0);
  16806. __decorate([
  16807. BABYLON.serialize()
  16808. ], Camera.prototype, "maxZ", void 0);
  16809. __decorate([
  16810. BABYLON.serialize()
  16811. ], Camera.prototype, "inertia", void 0);
  16812. __decorate([
  16813. BABYLON.serialize()
  16814. ], Camera.prototype, "mode", void 0);
  16815. __decorate([
  16816. BABYLON.serialize()
  16817. ], Camera.prototype, "layerMask", void 0);
  16818. __decorate([
  16819. BABYLON.serialize()
  16820. ], Camera.prototype, "fovMode", void 0);
  16821. __decorate([
  16822. BABYLON.serialize()
  16823. ], Camera.prototype, "cameraRigMode", void 0);
  16824. __decorate([
  16825. BABYLON.serialize()
  16826. ], Camera.prototype, "interaxialDistance", void 0);
  16827. __decorate([
  16828. BABYLON.serialize()
  16829. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16830. BABYLON.Camera = Camera;
  16831. })(BABYLON || (BABYLON = {}));
  16832. //# sourceMappingURL=babylon.camera.js.map
  16833. var BABYLON;
  16834. (function (BABYLON) {
  16835. BABYLON.CameraInputTypes = {};
  16836. var CameraInputsManager = (function () {
  16837. function CameraInputsManager(camera) {
  16838. this.attached = {};
  16839. this.camera = camera;
  16840. this.checkInputs = function () { };
  16841. }
  16842. CameraInputsManager.prototype.add = function (input) {
  16843. var type = input.getSimpleName();
  16844. if (this.attached[type]) {
  16845. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  16846. return;
  16847. }
  16848. this.attached[type] = input;
  16849. input.camera = this.camera;
  16850. //for checkInputs, we are dynamically creating a function
  16851. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  16852. if (input.checkInputs) {
  16853. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16854. }
  16855. if (this.attachedElement) {
  16856. input.attachControl(this.attachedElement);
  16857. }
  16858. };
  16859. CameraInputsManager.prototype.remove = function (inputToRemove) {
  16860. for (var cam in this.attached) {
  16861. var input = this.attached[cam];
  16862. if (input === inputToRemove) {
  16863. input.detachControl(this.attachedElement);
  16864. delete this.attached[cam];
  16865. this.rebuildInputCheck();
  16866. }
  16867. }
  16868. };
  16869. CameraInputsManager.prototype.removeByType = function (inputType) {
  16870. for (var cam in this.attached) {
  16871. var input = this.attached[cam];
  16872. if (input.getTypeName() === inputType) {
  16873. input.detachControl(this.attachedElement);
  16874. delete this.attached[cam];
  16875. this.rebuildInputCheck();
  16876. }
  16877. }
  16878. };
  16879. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  16880. var current = this.checkInputs;
  16881. return function () {
  16882. current();
  16883. fn();
  16884. };
  16885. };
  16886. CameraInputsManager.prototype.attachInput = function (input) {
  16887. input.attachControl(this.attachedElement, this.noPreventDefault);
  16888. };
  16889. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  16890. if (this.attachedElement) {
  16891. return;
  16892. }
  16893. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  16894. this.attachedElement = element;
  16895. this.noPreventDefault = noPreventDefault;
  16896. for (var cam in this.attached) {
  16897. var input = this.attached[cam];
  16898. this.attached[cam].attachControl(element, noPreventDefault);
  16899. }
  16900. };
  16901. CameraInputsManager.prototype.detachElement = function (element) {
  16902. if (this.attachedElement !== element) {
  16903. return;
  16904. }
  16905. for (var cam in this.attached) {
  16906. var input = this.attached[cam];
  16907. this.attached[cam].detachControl(element);
  16908. }
  16909. this.attachedElement = null;
  16910. };
  16911. CameraInputsManager.prototype.rebuildInputCheck = function () {
  16912. this.checkInputs = function () { };
  16913. for (var cam in this.attached) {
  16914. var input = this.attached[cam];
  16915. if (input.checkInputs) {
  16916. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16917. }
  16918. }
  16919. };
  16920. CameraInputsManager.prototype.clear = function () {
  16921. if (this.attachedElement) {
  16922. this.detachElement(this.attachedElement);
  16923. }
  16924. this.attached = {};
  16925. this.attachedElement = null;
  16926. this.checkInputs = function () { };
  16927. };
  16928. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  16929. var inputs = {};
  16930. for (var cam in this.attached) {
  16931. var input = this.attached[cam];
  16932. var res = BABYLON.SerializationHelper.Serialize(input);
  16933. inputs[input.getTypeName()] = res;
  16934. }
  16935. serializedCamera.inputsmgr = inputs;
  16936. };
  16937. CameraInputsManager.prototype.parse = function (parsedCamera) {
  16938. var parsedInputs = parsedCamera.inputsmgr;
  16939. if (parsedInputs) {
  16940. this.clear();
  16941. for (var n in parsedInputs) {
  16942. var construct = BABYLON.CameraInputTypes[n];
  16943. if (construct) {
  16944. var parsedinput = parsedInputs[n];
  16945. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  16946. this.add(input);
  16947. }
  16948. }
  16949. }
  16950. else {
  16951. //2016-03-08 this part is for managing backward compatibility
  16952. for (var n in this.attached) {
  16953. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  16954. if (construct) {
  16955. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  16956. this.remove(this.attached[n]);
  16957. this.add(input);
  16958. }
  16959. }
  16960. }
  16961. };
  16962. return CameraInputsManager;
  16963. }());
  16964. BABYLON.CameraInputsManager = CameraInputsManager;
  16965. })(BABYLON || (BABYLON = {}));
  16966. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  16967. var BABYLON;
  16968. (function (BABYLON) {
  16969. var FreeCameraMouseInput = (function () {
  16970. function FreeCameraMouseInput(touchEnabled) {
  16971. if (touchEnabled === void 0) { touchEnabled = true; }
  16972. this.touchEnabled = touchEnabled;
  16973. this.buttons = [0, 1, 2];
  16974. this.angularSensibility = 2000.0;
  16975. }
  16976. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  16977. var _this = this;
  16978. var engine = this.camera.getEngine();
  16979. if (!this._pointerInput) {
  16980. this._pointerInput = function (p, s) {
  16981. var evt = p.event;
  16982. if (!_this.touchEnabled && evt.pointerType === "touch") {
  16983. return;
  16984. }
  16985. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  16986. return;
  16987. }
  16988. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16989. try {
  16990. evt.srcElement.setPointerCapture(evt.pointerId);
  16991. }
  16992. catch (e) {
  16993. //Nothing to do with the error. Execution will continue.
  16994. }
  16995. _this.previousPosition = {
  16996. x: evt.clientX,
  16997. y: evt.clientY
  16998. };
  16999. if (!noPreventDefault) {
  17000. evt.preventDefault();
  17001. element.focus();
  17002. }
  17003. }
  17004. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  17005. try {
  17006. evt.srcElement.releasePointerCapture(evt.pointerId);
  17007. }
  17008. catch (e) {
  17009. //Nothing to do with the error.
  17010. }
  17011. _this.previousPosition = null;
  17012. if (!noPreventDefault) {
  17013. evt.preventDefault();
  17014. }
  17015. }
  17016. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  17017. if (!_this.previousPosition || engine.isPointerLock) {
  17018. return;
  17019. }
  17020. var offsetX = evt.clientX - _this.previousPosition.x;
  17021. var offsetY = evt.clientY - _this.previousPosition.y;
  17022. if (_this.camera.getScene().useRightHandedSystem) {
  17023. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  17024. }
  17025. else {
  17026. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  17027. }
  17028. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  17029. _this.previousPosition = {
  17030. x: evt.clientX,
  17031. y: evt.clientY
  17032. };
  17033. if (!noPreventDefault) {
  17034. evt.preventDefault();
  17035. }
  17036. }
  17037. };
  17038. }
  17039. this._onMouseMove = function (evt) {
  17040. if (!engine.isPointerLock) {
  17041. return;
  17042. }
  17043. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  17044. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  17045. if (_this.camera.getScene().useRightHandedSystem) {
  17046. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  17047. }
  17048. else {
  17049. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  17050. }
  17051. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  17052. _this.previousPosition = null;
  17053. if (!noPreventDefault) {
  17054. evt.preventDefault();
  17055. }
  17056. };
  17057. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  17058. element.addEventListener("mousemove", this._onMouseMove, false);
  17059. };
  17060. FreeCameraMouseInput.prototype.detachControl = function (element) {
  17061. if (this._observer && element) {
  17062. this.camera.getScene().onPointerObservable.remove(this._observer);
  17063. element.removeEventListener("mousemove", this._onMouseMove);
  17064. this._observer = null;
  17065. this._onMouseMove = null;
  17066. this.previousPosition = null;
  17067. }
  17068. };
  17069. FreeCameraMouseInput.prototype.getTypeName = function () {
  17070. return "FreeCameraMouseInput";
  17071. };
  17072. FreeCameraMouseInput.prototype.getSimpleName = function () {
  17073. return "mouse";
  17074. };
  17075. return FreeCameraMouseInput;
  17076. }());
  17077. __decorate([
  17078. BABYLON.serialize()
  17079. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  17080. __decorate([
  17081. BABYLON.serialize()
  17082. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  17083. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  17084. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  17085. })(BABYLON || (BABYLON = {}));
  17086. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  17087. var BABYLON;
  17088. (function (BABYLON) {
  17089. var FreeCameraKeyboardMoveInput = (function () {
  17090. function FreeCameraKeyboardMoveInput() {
  17091. this._keys = [];
  17092. this.keysUp = [38];
  17093. this.keysDown = [40];
  17094. this.keysLeft = [37];
  17095. this.keysRight = [39];
  17096. }
  17097. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  17098. var _this = this;
  17099. if (!this._onKeyDown) {
  17100. element.tabIndex = 1;
  17101. this._onKeyDown = function (evt) {
  17102. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17103. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17104. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17105. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17106. var index = _this._keys.indexOf(evt.keyCode);
  17107. if (index === -1) {
  17108. _this._keys.push(evt.keyCode);
  17109. }
  17110. if (!noPreventDefault) {
  17111. evt.preventDefault();
  17112. }
  17113. }
  17114. };
  17115. this._onKeyUp = function (evt) {
  17116. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17117. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17118. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17119. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17120. var index = _this._keys.indexOf(evt.keyCode);
  17121. if (index >= 0) {
  17122. _this._keys.splice(index, 1);
  17123. }
  17124. if (!noPreventDefault) {
  17125. evt.preventDefault();
  17126. }
  17127. }
  17128. };
  17129. element.addEventListener("keydown", this._onKeyDown, false);
  17130. element.addEventListener("keyup", this._onKeyUp, false);
  17131. BABYLON.Tools.RegisterTopRootEvents([
  17132. { name: "blur", handler: this._onLostFocus }
  17133. ]);
  17134. }
  17135. };
  17136. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  17137. if (this._onKeyDown) {
  17138. element.removeEventListener("keydown", this._onKeyDown);
  17139. element.removeEventListener("keyup", this._onKeyUp);
  17140. BABYLON.Tools.UnregisterTopRootEvents([
  17141. { name: "blur", handler: this._onLostFocus }
  17142. ]);
  17143. this._keys = [];
  17144. this._onKeyDown = null;
  17145. this._onKeyUp = null;
  17146. }
  17147. };
  17148. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  17149. if (this._onKeyDown) {
  17150. var camera = this.camera;
  17151. // Keyboard
  17152. for (var index = 0; index < this._keys.length; index++) {
  17153. var keyCode = this._keys[index];
  17154. var speed = camera._computeLocalCameraSpeed();
  17155. if (this.keysLeft.indexOf(keyCode) !== -1) {
  17156. camera._localDirection.copyFromFloats(-speed, 0, 0);
  17157. }
  17158. else if (this.keysUp.indexOf(keyCode) !== -1) {
  17159. camera._localDirection.copyFromFloats(0, 0, speed);
  17160. }
  17161. else if (this.keysRight.indexOf(keyCode) !== -1) {
  17162. camera._localDirection.copyFromFloats(speed, 0, 0);
  17163. }
  17164. else if (this.keysDown.indexOf(keyCode) !== -1) {
  17165. camera._localDirection.copyFromFloats(0, 0, -speed);
  17166. }
  17167. if (camera.getScene().useRightHandedSystem) {
  17168. camera._localDirection.z *= -1;
  17169. }
  17170. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  17171. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  17172. camera.cameraDirection.addInPlace(camera._transformedDirection);
  17173. }
  17174. }
  17175. };
  17176. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  17177. return "FreeCameraKeyboardMoveInput";
  17178. };
  17179. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  17180. this._keys = [];
  17181. };
  17182. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  17183. return "keyboard";
  17184. };
  17185. return FreeCameraKeyboardMoveInput;
  17186. }());
  17187. __decorate([
  17188. BABYLON.serialize()
  17189. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  17190. __decorate([
  17191. BABYLON.serialize()
  17192. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  17193. __decorate([
  17194. BABYLON.serialize()
  17195. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  17196. __decorate([
  17197. BABYLON.serialize()
  17198. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  17199. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  17200. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  17201. })(BABYLON || (BABYLON = {}));
  17202. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  17203. var BABYLON;
  17204. (function (BABYLON) {
  17205. var FreeCameraTouchInput = (function () {
  17206. function FreeCameraTouchInput() {
  17207. this._offsetX = null;
  17208. this._offsetY = null;
  17209. this._pointerCount = 0;
  17210. this._pointerPressed = [];
  17211. this.touchAngularSensibility = 200000.0;
  17212. this.touchMoveSensibility = 250.0;
  17213. }
  17214. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  17215. var _this = this;
  17216. var previousPosition;
  17217. if (this._pointerInput === undefined) {
  17218. this._onLostFocus = function (evt) {
  17219. _this._offsetX = null;
  17220. _this._offsetY = null;
  17221. };
  17222. this._pointerInput = function (p, s) {
  17223. var evt = p.event;
  17224. if (evt.pointerType === "mouse") {
  17225. return;
  17226. }
  17227. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  17228. if (!noPreventDefault) {
  17229. evt.preventDefault();
  17230. }
  17231. _this._pointerPressed.push(evt.pointerId);
  17232. if (_this._pointerPressed.length !== 1) {
  17233. return;
  17234. }
  17235. previousPosition = {
  17236. x: evt.clientX,
  17237. y: evt.clientY
  17238. };
  17239. }
  17240. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  17241. if (!noPreventDefault) {
  17242. evt.preventDefault();
  17243. }
  17244. var index = _this._pointerPressed.indexOf(evt.pointerId);
  17245. if (index === -1) {
  17246. return;
  17247. }
  17248. _this._pointerPressed.splice(index, 1);
  17249. if (index != 0) {
  17250. return;
  17251. }
  17252. previousPosition = null;
  17253. _this._offsetX = null;
  17254. _this._offsetY = null;
  17255. }
  17256. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  17257. if (!noPreventDefault) {
  17258. evt.preventDefault();
  17259. }
  17260. if (!previousPosition) {
  17261. return;
  17262. }
  17263. var index = _this._pointerPressed.indexOf(evt.pointerId);
  17264. if (index != 0) {
  17265. return;
  17266. }
  17267. _this._offsetX = evt.clientX - previousPosition.x;
  17268. _this._offsetY = -(evt.clientY - previousPosition.y);
  17269. }
  17270. };
  17271. }
  17272. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  17273. element.addEventListener("blur", this._onLostFocus);
  17274. };
  17275. FreeCameraTouchInput.prototype.detachControl = function (element) {
  17276. if (this._pointerInput && element) {
  17277. this.camera.getScene().onPointerObservable.remove(this._observer);
  17278. this._observer = null;
  17279. element.removeEventListener("blur", this._onLostFocus);
  17280. this._onLostFocus = null;
  17281. this._pointerPressed = [];
  17282. this._offsetX = null;
  17283. this._offsetY = null;
  17284. this._pointerCount = 0;
  17285. }
  17286. };
  17287. FreeCameraTouchInput.prototype.checkInputs = function () {
  17288. if (this._offsetX) {
  17289. var camera = this.camera;
  17290. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  17291. if (this._pointerPressed.length > 1) {
  17292. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  17293. }
  17294. else {
  17295. var speed = camera._computeLocalCameraSpeed();
  17296. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  17297. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  17298. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  17299. }
  17300. }
  17301. };
  17302. FreeCameraTouchInput.prototype.getTypeName = function () {
  17303. return "FreeCameraTouchInput";
  17304. };
  17305. FreeCameraTouchInput.prototype.getSimpleName = function () {
  17306. return "touch";
  17307. };
  17308. return FreeCameraTouchInput;
  17309. }());
  17310. __decorate([
  17311. BABYLON.serialize()
  17312. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  17313. __decorate([
  17314. BABYLON.serialize()
  17315. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  17316. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  17317. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  17318. })(BABYLON || (BABYLON = {}));
  17319. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  17320. var BABYLON;
  17321. (function (BABYLON) {
  17322. var FreeCameraDeviceOrientationInput = (function () {
  17323. function FreeCameraDeviceOrientationInput() {
  17324. var _this = this;
  17325. this._screenOrientationAngle = 0;
  17326. this._screenQuaternion = new BABYLON.Quaternion();
  17327. this._alpha = 0;
  17328. this._beta = 0;
  17329. this._gamma = 0;
  17330. this._orientationChanged = function () {
  17331. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  17332. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  17333. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  17334. };
  17335. this._deviceOrientation = function (evt) {
  17336. _this._alpha = evt.alpha;
  17337. _this._beta = evt.beta;
  17338. _this._gamma = evt.gamma;
  17339. };
  17340. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  17341. this._orientationChanged();
  17342. }
  17343. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  17344. get: function () {
  17345. return this._camera;
  17346. },
  17347. set: function (camera) {
  17348. this._camera = camera;
  17349. if (!this._camera.rotationQuaternion)
  17350. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  17351. },
  17352. enumerable: true,
  17353. configurable: true
  17354. });
  17355. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  17356. window.addEventListener("orientationchange", this._orientationChanged);
  17357. window.addEventListener("deviceorientation", this._deviceOrientation);
  17358. //In certain cases, the attach control is called AFTER orientation was changed,
  17359. //So this is needed.
  17360. this._orientationChanged();
  17361. };
  17362. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  17363. window.removeEventListener("orientationchange", this._orientationChanged);
  17364. window.removeEventListener("deviceorientation", this._deviceOrientation);
  17365. };
  17366. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  17367. //if no device orientation provided, don't update the rotation.
  17368. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  17369. if (!this._alpha)
  17370. return;
  17371. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  17372. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  17373. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  17374. //Mirror on XY Plane
  17375. this._camera.rotationQuaternion.z *= -1;
  17376. this._camera.rotationQuaternion.w *= -1;
  17377. };
  17378. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  17379. return "FreeCameraDeviceOrientationInput";
  17380. };
  17381. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  17382. return "deviceOrientation";
  17383. };
  17384. return FreeCameraDeviceOrientationInput;
  17385. }());
  17386. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  17387. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  17388. })(BABYLON || (BABYLON = {}));
  17389. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  17390. var BABYLON;
  17391. (function (BABYLON) {
  17392. var FreeCameraGamepadInput = (function () {
  17393. function FreeCameraGamepadInput() {
  17394. this.gamepadAngularSensibility = 200;
  17395. this.gamepadMoveSensibility = 40;
  17396. // private members
  17397. this._cameraTransform = BABYLON.Matrix.Identity();
  17398. this._deltaTransform = BABYLON.Vector3.Zero();
  17399. this._vector3 = BABYLON.Vector3.Zero();
  17400. this._vector2 = BABYLON.Vector2.Zero();
  17401. }
  17402. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  17403. var _this = this;
  17404. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  17405. };
  17406. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  17407. if (this._gamepads) {
  17408. this._gamepads.dispose();
  17409. }
  17410. this.gamepad = null;
  17411. };
  17412. FreeCameraGamepadInput.prototype.checkInputs = function () {
  17413. if (this.gamepad && this.gamepad.leftStick) {
  17414. var camera = this.camera;
  17415. var LSValues = this.gamepad.leftStick;
  17416. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  17417. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  17418. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  17419. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  17420. var RSValues = this.gamepad.rightStick;
  17421. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  17422. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  17423. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  17424. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  17425. if (!camera.rotationQuaternion) {
  17426. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  17427. }
  17428. else {
  17429. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  17430. }
  17431. var speed = camera._computeLocalCameraSpeed() * 50.0;
  17432. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  17433. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  17434. camera.cameraDirection.addInPlace(this._deltaTransform);
  17435. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  17436. camera.cameraRotation.addInPlace(this._vector2);
  17437. }
  17438. };
  17439. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  17440. // Only the first gamepad found can control the camera
  17441. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  17442. // prioritize XBOX gamepads.
  17443. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  17444. this.gamepad = gamepad;
  17445. }
  17446. }
  17447. };
  17448. FreeCameraGamepadInput.prototype.getTypeName = function () {
  17449. return "FreeCameraGamepadInput";
  17450. };
  17451. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  17452. return "gamepad";
  17453. };
  17454. return FreeCameraGamepadInput;
  17455. }());
  17456. __decorate([
  17457. BABYLON.serialize()
  17458. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  17459. __decorate([
  17460. BABYLON.serialize()
  17461. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17462. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  17463. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  17464. })(BABYLON || (BABYLON = {}));
  17465. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  17466. var BABYLON;
  17467. (function (BABYLON) {
  17468. var ArcRotateCameraKeyboardMoveInput = (function () {
  17469. function ArcRotateCameraKeyboardMoveInput() {
  17470. this._keys = [];
  17471. this.keysUp = [38];
  17472. this.keysDown = [40];
  17473. this.keysLeft = [37];
  17474. this.keysRight = [39];
  17475. }
  17476. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  17477. var _this = this;
  17478. element.tabIndex = 1;
  17479. this._onKeyDown = function (evt) {
  17480. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17481. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17482. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17483. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17484. var index = _this._keys.indexOf(evt.keyCode);
  17485. if (index === -1) {
  17486. _this._keys.push(evt.keyCode);
  17487. }
  17488. if (evt.preventDefault) {
  17489. if (!noPreventDefault) {
  17490. evt.preventDefault();
  17491. }
  17492. }
  17493. }
  17494. };
  17495. this._onKeyUp = function (evt) {
  17496. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17497. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17498. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17499. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17500. var index = _this._keys.indexOf(evt.keyCode);
  17501. if (index >= 0) {
  17502. _this._keys.splice(index, 1);
  17503. }
  17504. if (evt.preventDefault) {
  17505. if (!noPreventDefault) {
  17506. evt.preventDefault();
  17507. }
  17508. }
  17509. }
  17510. };
  17511. this._onLostFocus = function () {
  17512. _this._keys = [];
  17513. };
  17514. element.addEventListener("keydown", this._onKeyDown, false);
  17515. element.addEventListener("keyup", this._onKeyUp, false);
  17516. BABYLON.Tools.RegisterTopRootEvents([
  17517. { name: "blur", handler: this._onLostFocus }
  17518. ]);
  17519. };
  17520. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  17521. if (element) {
  17522. element.removeEventListener("keydown", this._onKeyDown);
  17523. element.removeEventListener("keyup", this._onKeyUp);
  17524. }
  17525. BABYLON.Tools.UnregisterTopRootEvents([
  17526. { name: "blur", handler: this._onLostFocus }
  17527. ]);
  17528. this._keys = [];
  17529. this._onKeyDown = null;
  17530. this._onKeyUp = null;
  17531. this._onLostFocus = null;
  17532. };
  17533. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  17534. if (this._onKeyDown) {
  17535. var camera = this.camera;
  17536. for (var index = 0; index < this._keys.length; index++) {
  17537. var keyCode = this._keys[index];
  17538. if (this.keysLeft.indexOf(keyCode) !== -1) {
  17539. camera.inertialAlphaOffset -= 0.01;
  17540. }
  17541. else if (this.keysUp.indexOf(keyCode) !== -1) {
  17542. camera.inertialBetaOffset -= 0.01;
  17543. }
  17544. else if (this.keysRight.indexOf(keyCode) !== -1) {
  17545. camera.inertialAlphaOffset += 0.01;
  17546. }
  17547. else if (this.keysDown.indexOf(keyCode) !== -1) {
  17548. camera.inertialBetaOffset += 0.01;
  17549. }
  17550. }
  17551. }
  17552. };
  17553. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  17554. return "ArcRotateCameraKeyboardMoveInput";
  17555. };
  17556. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  17557. return "keyboard";
  17558. };
  17559. return ArcRotateCameraKeyboardMoveInput;
  17560. }());
  17561. __decorate([
  17562. BABYLON.serialize()
  17563. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  17564. __decorate([
  17565. BABYLON.serialize()
  17566. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  17567. __decorate([
  17568. BABYLON.serialize()
  17569. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  17570. __decorate([
  17571. BABYLON.serialize()
  17572. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  17573. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  17574. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  17575. })(BABYLON || (BABYLON = {}));
  17576. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  17577. var BABYLON;
  17578. (function (BABYLON) {
  17579. var ArcRotateCameraMouseWheelInput = (function () {
  17580. function ArcRotateCameraMouseWheelInput() {
  17581. this.wheelPrecision = 3.0;
  17582. }
  17583. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  17584. var _this = this;
  17585. this._wheel = function (p, s) {
  17586. //sanity check - this should be a PointerWheel event.
  17587. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  17588. return;
  17589. var event = p.event;
  17590. var delta = 0;
  17591. if (event.wheelDelta) {
  17592. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  17593. }
  17594. else if (event.detail) {
  17595. delta = -event.detail / _this.wheelPrecision;
  17596. }
  17597. if (delta)
  17598. _this.camera.inertialRadiusOffset += delta;
  17599. if (event.preventDefault) {
  17600. if (!noPreventDefault) {
  17601. event.preventDefault();
  17602. }
  17603. }
  17604. };
  17605. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  17606. };
  17607. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  17608. if (this._observer && element) {
  17609. this.camera.getScene().onPointerObservable.remove(this._observer);
  17610. this._observer = null;
  17611. this._wheel = null;
  17612. }
  17613. };
  17614. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  17615. return "ArcRotateCameraMouseWheelInput";
  17616. };
  17617. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  17618. return "mousewheel";
  17619. };
  17620. return ArcRotateCameraMouseWheelInput;
  17621. }());
  17622. __decorate([
  17623. BABYLON.serialize()
  17624. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  17625. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  17626. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  17627. })(BABYLON || (BABYLON = {}));
  17628. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  17629. var BABYLON;
  17630. (function (BABYLON) {
  17631. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17632. var ArcRotateCameraPointersInput = (function () {
  17633. function ArcRotateCameraPointersInput() {
  17634. this.buttons = [0, 1, 2];
  17635. this.angularSensibilityX = 1000.0;
  17636. this.angularSensibilityY = 1000.0;
  17637. this.pinchPrecision = 6.0;
  17638. this.panningSensibility = 50.0;
  17639. this._isPanClick = false;
  17640. this.pinchInwards = true;
  17641. }
  17642. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  17643. var _this = this;
  17644. var engine = this.camera.getEngine();
  17645. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  17646. var pointA, pointB;
  17647. var previousPinchDistance = 0;
  17648. this._pointerInput = function (p, s) {
  17649. var evt = p.event;
  17650. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  17651. return;
  17652. }
  17653. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  17654. try {
  17655. evt.srcElement.setPointerCapture(evt.pointerId);
  17656. }
  17657. catch (e) {
  17658. //Nothing to do with the error. Execution will continue.
  17659. }
  17660. // Manage panning with pan button click
  17661. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  17662. // manage pointers
  17663. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  17664. if (pointA === undefined) {
  17665. pointA = cacheSoloPointer;
  17666. }
  17667. else if (pointB === undefined) {
  17668. pointB = cacheSoloPointer;
  17669. }
  17670. if (!noPreventDefault) {
  17671. evt.preventDefault();
  17672. element.focus();
  17673. }
  17674. }
  17675. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  17676. try {
  17677. evt.srcElement.releasePointerCapture(evt.pointerId);
  17678. }
  17679. catch (e) {
  17680. //Nothing to do with the error.
  17681. }
  17682. cacheSoloPointer = null;
  17683. previousPinchDistance = 0;
  17684. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  17685. //but emptying completly pointers collection is required to fix a bug on iPhone :
  17686. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  17687. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  17688. pointA = pointB = undefined;
  17689. if (!noPreventDefault) {
  17690. evt.preventDefault();
  17691. }
  17692. }
  17693. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  17694. if (!noPreventDefault) {
  17695. evt.preventDefault();
  17696. }
  17697. // One button down
  17698. if (pointA && pointB === undefined) {
  17699. if (_this.panningSensibility !== 0 &&
  17700. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  17701. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  17702. _this.camera
  17703. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  17704. _this.camera
  17705. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  17706. }
  17707. else {
  17708. var offsetX = evt.clientX - cacheSoloPointer.x;
  17709. var offsetY = evt.clientY - cacheSoloPointer.y;
  17710. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17711. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17712. }
  17713. cacheSoloPointer.x = evt.clientX;
  17714. cacheSoloPointer.y = evt.clientY;
  17715. }
  17716. else if (pointA && pointB) {
  17717. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  17718. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  17719. ed.x = evt.clientX;
  17720. ed.y = evt.clientY;
  17721. var direction = _this.pinchInwards ? 1 : -1;
  17722. var distX = pointA.x - pointB.x;
  17723. var distY = pointA.y - pointB.y;
  17724. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  17725. if (previousPinchDistance === 0) {
  17726. previousPinchDistance = pinchSquaredDistance;
  17727. return;
  17728. }
  17729. if (pinchSquaredDistance !== previousPinchDistance) {
  17730. _this.camera
  17731. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  17732. (_this.pinchPrecision *
  17733. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  17734. direction);
  17735. previousPinchDistance = pinchSquaredDistance;
  17736. }
  17737. }
  17738. }
  17739. };
  17740. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  17741. this._onContextMenu = function (evt) {
  17742. evt.preventDefault();
  17743. };
  17744. if (!this.camera._useCtrlForPanning) {
  17745. element.addEventListener("contextmenu", this._onContextMenu, false);
  17746. }
  17747. this._onLostFocus = function () {
  17748. //this._keys = [];
  17749. pointA = pointB = undefined;
  17750. previousPinchDistance = 0;
  17751. cacheSoloPointer = null;
  17752. };
  17753. this._onMouseMove = function (evt) {
  17754. if (!engine.isPointerLock) {
  17755. return;
  17756. }
  17757. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  17758. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  17759. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17760. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17761. if (!noPreventDefault) {
  17762. evt.preventDefault();
  17763. }
  17764. };
  17765. this._onGestureStart = function (e) {
  17766. if (window.MSGesture === undefined) {
  17767. return;
  17768. }
  17769. if (!_this._MSGestureHandler) {
  17770. _this._MSGestureHandler = new MSGesture();
  17771. _this._MSGestureHandler.target = element;
  17772. }
  17773. _this._MSGestureHandler.addPointer(e.pointerId);
  17774. };
  17775. this._onGesture = function (e) {
  17776. _this.camera.radius *= e.scale;
  17777. if (e.preventDefault) {
  17778. if (!noPreventDefault) {
  17779. e.stopPropagation();
  17780. e.preventDefault();
  17781. }
  17782. }
  17783. };
  17784. element.addEventListener("mousemove", this._onMouseMove, false);
  17785. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  17786. element.addEventListener("MSGestureChange", this._onGesture, false);
  17787. element.addEventListener("keydown", this._onKeyDown, false);
  17788. element.addEventListener("keyup", this._onKeyUp, false);
  17789. BABYLON.Tools.RegisterTopRootEvents([
  17790. { name: "blur", handler: this._onLostFocus }
  17791. ]);
  17792. };
  17793. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  17794. if (element && this._observer) {
  17795. this.camera.getScene().onPointerObservable.remove(this._observer);
  17796. this._observer = null;
  17797. element.removeEventListener("contextmenu", this._onContextMenu);
  17798. element.removeEventListener("mousemove", this._onMouseMove);
  17799. element.removeEventListener("MSPointerDown", this._onGestureStart);
  17800. element.removeEventListener("MSGestureChange", this._onGesture);
  17801. element.removeEventListener("keydown", this._onKeyDown);
  17802. element.removeEventListener("keyup", this._onKeyUp);
  17803. this._isPanClick = false;
  17804. this.pinchInwards = true;
  17805. this._onKeyDown = null;
  17806. this._onKeyUp = null;
  17807. this._onMouseMove = null;
  17808. this._onGestureStart = null;
  17809. this._onGesture = null;
  17810. this._MSGestureHandler = null;
  17811. this._onLostFocus = null;
  17812. this._onContextMenu = null;
  17813. }
  17814. BABYLON.Tools.UnregisterTopRootEvents([
  17815. { name: "blur", handler: this._onLostFocus }
  17816. ]);
  17817. };
  17818. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  17819. return "ArcRotateCameraPointersInput";
  17820. };
  17821. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  17822. return "pointers";
  17823. };
  17824. return ArcRotateCameraPointersInput;
  17825. }());
  17826. __decorate([
  17827. BABYLON.serialize()
  17828. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  17829. __decorate([
  17830. BABYLON.serialize()
  17831. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  17832. __decorate([
  17833. BABYLON.serialize()
  17834. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  17835. __decorate([
  17836. BABYLON.serialize()
  17837. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  17838. __decorate([
  17839. BABYLON.serialize()
  17840. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  17841. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  17842. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  17843. })(BABYLON || (BABYLON = {}));
  17844. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  17845. var BABYLON;
  17846. (function (BABYLON) {
  17847. var ArcRotateCameraGamepadInput = (function () {
  17848. function ArcRotateCameraGamepadInput() {
  17849. this.gamepadRotationSensibility = 80;
  17850. this.gamepadMoveSensibility = 40;
  17851. }
  17852. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  17853. var _this = this;
  17854. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  17855. };
  17856. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  17857. if (this._gamepads) {
  17858. this._gamepads.dispose();
  17859. }
  17860. this.gamepad = null;
  17861. };
  17862. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  17863. if (this.gamepad) {
  17864. var camera = this.camera;
  17865. var RSValues = this.gamepad.rightStick;
  17866. if (RSValues.x != 0) {
  17867. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  17868. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  17869. camera.inertialAlphaOffset += normalizedRX;
  17870. }
  17871. }
  17872. if (RSValues.y != 0) {
  17873. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  17874. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  17875. camera.inertialBetaOffset += normalizedRY;
  17876. }
  17877. }
  17878. var LSValues = this.gamepad.leftStick;
  17879. if (LSValues.y != 0) {
  17880. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  17881. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  17882. this.camera.inertialRadiusOffset -= normalizedLY;
  17883. }
  17884. }
  17885. }
  17886. };
  17887. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  17888. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  17889. // prioritize XBOX gamepads.
  17890. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  17891. this.gamepad = gamepad;
  17892. }
  17893. }
  17894. };
  17895. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  17896. return "ArcRotateCameraGamepadInput";
  17897. };
  17898. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  17899. return "gamepad";
  17900. };
  17901. return ArcRotateCameraGamepadInput;
  17902. }());
  17903. __decorate([
  17904. BABYLON.serialize()
  17905. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  17906. __decorate([
  17907. BABYLON.serialize()
  17908. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17909. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  17910. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  17911. })(BABYLON || (BABYLON = {}));
  17912. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  17913. var BABYLON;
  17914. (function (BABYLON) {
  17915. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  17916. function ArcRotateCameraVRDeviceOrientationInput() {
  17917. this.alphaCorrection = 1;
  17918. this.betaCorrection = 1;
  17919. this.gammaCorrection = 1;
  17920. this._alpha = 0;
  17921. this._beta = 0;
  17922. this._gamma = 0;
  17923. this._dirty = false;
  17924. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17925. }
  17926. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  17927. this.camera.attachControl(element, noPreventDefault);
  17928. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17929. };
  17930. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  17931. var camera = this.camera;
  17932. this._alpha = +evt.alpha | 0;
  17933. this._beta = +evt.beta | 0;
  17934. this._gamma = +evt.gamma | 0;
  17935. this._dirty = true;
  17936. };
  17937. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  17938. if (this._dirty) {
  17939. this._dirty = false;
  17940. if (this._gamma < 0) {
  17941. this._gamma = 180 + this._gamma;
  17942. }
  17943. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  17944. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  17945. }
  17946. };
  17947. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  17948. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17949. };
  17950. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  17951. return "ArcRotateCameraVRDeviceOrientationInput";
  17952. };
  17953. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  17954. return "VRDeviceOrientation";
  17955. };
  17956. return ArcRotateCameraVRDeviceOrientationInput;
  17957. }());
  17958. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  17959. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  17960. })(BABYLON || (BABYLON = {}));
  17961. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  17962. /// <reference path="babylon.camera.ts" />
  17963. var BABYLON;
  17964. (function (BABYLON) {
  17965. var TargetCamera = (function (_super) {
  17966. __extends(TargetCamera, _super);
  17967. function TargetCamera(name, position, scene) {
  17968. var _this = _super.call(this, name, position, scene) || this;
  17969. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17970. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  17971. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  17972. _this.speed = 2.0;
  17973. _this.noRotationConstraint = false;
  17974. _this.lockedTarget = null;
  17975. _this._currentTarget = BABYLON.Vector3.Zero();
  17976. _this._viewMatrix = BABYLON.Matrix.Zero();
  17977. _this._camMatrix = BABYLON.Matrix.Zero();
  17978. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  17979. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  17980. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  17981. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  17982. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  17983. _this._lookAtTemp = BABYLON.Matrix.Zero();
  17984. _this._tempMatrix = BABYLON.Matrix.Zero();
  17985. return _this;
  17986. }
  17987. TargetCamera.prototype.getFrontPosition = function (distance) {
  17988. var direction = this.getTarget().subtract(this.position);
  17989. direction.normalize();
  17990. direction.scaleInPlace(distance);
  17991. return this.globalPosition.add(direction);
  17992. };
  17993. TargetCamera.prototype._getLockedTargetPosition = function () {
  17994. if (!this.lockedTarget) {
  17995. return null;
  17996. }
  17997. if (this.lockedTarget.absolutePosition) {
  17998. this.lockedTarget.computeWorldMatrix();
  17999. }
  18000. return this.lockedTarget.absolutePosition || this.lockedTarget;
  18001. };
  18002. // Cache
  18003. TargetCamera.prototype._initCache = function () {
  18004. _super.prototype._initCache.call(this);
  18005. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18006. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18007. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18008. };
  18009. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  18010. if (!ignoreParentClass) {
  18011. _super.prototype._updateCache.call(this);
  18012. }
  18013. var lockedTargetPosition = this._getLockedTargetPosition();
  18014. if (!lockedTargetPosition) {
  18015. this._cache.lockedTarget = null;
  18016. }
  18017. else {
  18018. if (!this._cache.lockedTarget) {
  18019. this._cache.lockedTarget = lockedTargetPosition.clone();
  18020. }
  18021. else {
  18022. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  18023. }
  18024. }
  18025. this._cache.rotation.copyFrom(this.rotation);
  18026. if (this.rotationQuaternion)
  18027. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18028. };
  18029. // Synchronized
  18030. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  18031. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  18032. return false;
  18033. }
  18034. var lockedTargetPosition = this._getLockedTargetPosition();
  18035. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  18036. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  18037. };
  18038. // Methods
  18039. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  18040. var engine = this.getEngine();
  18041. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  18042. };
  18043. // Target
  18044. TargetCamera.prototype.setTarget = function (target) {
  18045. this.upVector.normalize();
  18046. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  18047. this._camMatrix.invert();
  18048. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  18049. var vDir = target.subtract(this.position);
  18050. if (vDir.x >= 0.0) {
  18051. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  18052. }
  18053. else {
  18054. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  18055. }
  18056. this.rotation.z = 0;
  18057. if (isNaN(this.rotation.x)) {
  18058. this.rotation.x = 0;
  18059. }
  18060. if (isNaN(this.rotation.y)) {
  18061. this.rotation.y = 0;
  18062. }
  18063. if (isNaN(this.rotation.z)) {
  18064. this.rotation.z = 0;
  18065. }
  18066. if (this.rotationQuaternion) {
  18067. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  18068. }
  18069. };
  18070. /**
  18071. * Return the current target position of the camera. This value is expressed in local space.
  18072. */
  18073. TargetCamera.prototype.getTarget = function () {
  18074. return this._currentTarget;
  18075. };
  18076. TargetCamera.prototype._decideIfNeedsToMove = function () {
  18077. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  18078. };
  18079. TargetCamera.prototype._updatePosition = function () {
  18080. if (this.parent) {
  18081. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  18082. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  18083. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  18084. return;
  18085. }
  18086. this.position.addInPlace(this.cameraDirection);
  18087. };
  18088. TargetCamera.prototype._checkInputs = function () {
  18089. var needToMove = this._decideIfNeedsToMove();
  18090. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  18091. // Move
  18092. if (needToMove) {
  18093. this._updatePosition();
  18094. }
  18095. // Rotate
  18096. if (needToRotate) {
  18097. this.rotation.x += this.cameraRotation.x;
  18098. this.rotation.y += this.cameraRotation.y;
  18099. //rotate, if quaternion is set and rotation was used
  18100. if (this.rotationQuaternion) {
  18101. var len = this.rotation.lengthSquared();
  18102. if (len) {
  18103. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  18104. }
  18105. }
  18106. if (!this.noRotationConstraint) {
  18107. var limit = (Math.PI / 2) * 0.95;
  18108. if (this.rotation.x > limit)
  18109. this.rotation.x = limit;
  18110. if (this.rotation.x < -limit)
  18111. this.rotation.x = -limit;
  18112. }
  18113. }
  18114. // Inertia
  18115. if (needToMove) {
  18116. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  18117. this.cameraDirection.x = 0;
  18118. }
  18119. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  18120. this.cameraDirection.y = 0;
  18121. }
  18122. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  18123. this.cameraDirection.z = 0;
  18124. }
  18125. this.cameraDirection.scaleInPlace(this.inertia);
  18126. }
  18127. if (needToRotate) {
  18128. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  18129. this.cameraRotation.x = 0;
  18130. }
  18131. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  18132. this.cameraRotation.y = 0;
  18133. }
  18134. this.cameraRotation.scaleInPlace(this.inertia);
  18135. }
  18136. _super.prototype._checkInputs.call(this);
  18137. };
  18138. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  18139. if (this.rotationQuaternion) {
  18140. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  18141. //update the up vector!
  18142. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  18143. }
  18144. else {
  18145. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  18146. }
  18147. };
  18148. TargetCamera.prototype._getViewMatrix = function () {
  18149. if (!this.lockedTarget) {
  18150. // Compute
  18151. this._updateCameraRotationMatrix();
  18152. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  18153. // Computing target and final matrix
  18154. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  18155. }
  18156. else {
  18157. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  18158. }
  18159. if (this.getScene().useRightHandedSystem) {
  18160. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  18161. }
  18162. else {
  18163. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  18164. }
  18165. return this._viewMatrix;
  18166. };
  18167. /**
  18168. * @override
  18169. * Override Camera.createRigCamera
  18170. */
  18171. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  18172. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  18173. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  18174. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  18175. if (!this.rotationQuaternion) {
  18176. this.rotationQuaternion = new BABYLON.Quaternion();
  18177. }
  18178. rigCamera._cameraRigParams = {};
  18179. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  18180. }
  18181. return rigCamera;
  18182. }
  18183. return null;
  18184. };
  18185. /**
  18186. * @override
  18187. * Override Camera._updateRigCameras
  18188. */
  18189. TargetCamera.prototype._updateRigCameras = function () {
  18190. var camLeft = this._rigCameras[0];
  18191. var camRight = this._rigCameras[1];
  18192. switch (this.cameraRigMode) {
  18193. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18194. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18195. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18196. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18197. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  18198. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  18199. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  18200. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  18201. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  18202. camLeft.setTarget(this.getTarget());
  18203. camRight.setTarget(this.getTarget());
  18204. break;
  18205. case BABYLON.Camera.RIG_MODE_VR:
  18206. if (camLeft.rotationQuaternion) {
  18207. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18208. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18209. }
  18210. else {
  18211. camLeft.rotation.copyFrom(this.rotation);
  18212. camRight.rotation.copyFrom(this.rotation);
  18213. }
  18214. camLeft.position.copyFrom(this.position);
  18215. camRight.position.copyFrom(this.position);
  18216. break;
  18217. }
  18218. _super.prototype._updateRigCameras.call(this);
  18219. };
  18220. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  18221. if (!this._rigCamTransformMatrix) {
  18222. this._rigCamTransformMatrix = new BABYLON.Matrix();
  18223. }
  18224. var target = this.getTarget();
  18225. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  18226. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  18227. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  18228. };
  18229. TargetCamera.prototype.getClassName = function () {
  18230. return "TargetCamera";
  18231. };
  18232. return TargetCamera;
  18233. }(BABYLON.Camera));
  18234. __decorate([
  18235. BABYLON.serializeAsVector3()
  18236. ], TargetCamera.prototype, "rotation", void 0);
  18237. __decorate([
  18238. BABYLON.serialize()
  18239. ], TargetCamera.prototype, "speed", void 0);
  18240. __decorate([
  18241. BABYLON.serializeAsMeshReference("lockedTargetId")
  18242. ], TargetCamera.prototype, "lockedTarget", void 0);
  18243. BABYLON.TargetCamera = TargetCamera;
  18244. })(BABYLON || (BABYLON = {}));
  18245. //# sourceMappingURL=babylon.targetCamera.js.map
  18246. var BABYLON;
  18247. (function (BABYLON) {
  18248. var FreeCamera = (function (_super) {
  18249. __extends(FreeCamera, _super);
  18250. function FreeCamera(name, position, scene) {
  18251. var _this = _super.call(this, name, position, scene) || this;
  18252. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  18253. _this.checkCollisions = false;
  18254. _this.applyGravity = false;
  18255. _this._collider = new BABYLON.Collider();
  18256. _this._needMoveForGravity = false;
  18257. _this._oldPosition = BABYLON.Vector3.Zero();
  18258. _this._diffPosition = BABYLON.Vector3.Zero();
  18259. _this._newPosition = BABYLON.Vector3.Zero();
  18260. // Collisions
  18261. _this._collisionMask = -1;
  18262. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  18263. if (collidedMesh === void 0) { collidedMesh = null; }
  18264. //TODO move this to the collision coordinator!
  18265. if (_this.getScene().workerCollisions)
  18266. newPosition.multiplyInPlace(_this._collider.radius);
  18267. var updatePosition = function (newPos) {
  18268. _this._newPosition.copyFrom(newPos);
  18269. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  18270. var oldPosition = _this.position.clone();
  18271. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  18272. _this.position.addInPlace(_this._diffPosition);
  18273. if (_this.onCollide && collidedMesh) {
  18274. _this.onCollide(collidedMesh);
  18275. }
  18276. }
  18277. };
  18278. updatePosition(newPosition);
  18279. };
  18280. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  18281. _this.inputs.addKeyboard().addMouse();
  18282. return _this;
  18283. }
  18284. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  18285. //-- begin properties for backward compatibility for inputs
  18286. get: function () {
  18287. var mouse = this.inputs.attached["mouse"];
  18288. if (mouse)
  18289. return mouse.angularSensibility;
  18290. },
  18291. set: function (value) {
  18292. var mouse = this.inputs.attached["mouse"];
  18293. if (mouse)
  18294. mouse.angularSensibility = value;
  18295. },
  18296. enumerable: true,
  18297. configurable: true
  18298. });
  18299. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  18300. get: function () {
  18301. var keyboard = this.inputs.attached["keyboard"];
  18302. if (keyboard)
  18303. return keyboard.keysUp;
  18304. },
  18305. set: function (value) {
  18306. var keyboard = this.inputs.attached["keyboard"];
  18307. if (keyboard)
  18308. keyboard.keysUp = value;
  18309. },
  18310. enumerable: true,
  18311. configurable: true
  18312. });
  18313. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  18314. get: function () {
  18315. var keyboard = this.inputs.attached["keyboard"];
  18316. if (keyboard)
  18317. return keyboard.keysDown;
  18318. },
  18319. set: function (value) {
  18320. var keyboard = this.inputs.attached["keyboard"];
  18321. if (keyboard)
  18322. keyboard.keysDown = value;
  18323. },
  18324. enumerable: true,
  18325. configurable: true
  18326. });
  18327. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  18328. get: function () {
  18329. var keyboard = this.inputs.attached["keyboard"];
  18330. if (keyboard)
  18331. return keyboard.keysLeft;
  18332. },
  18333. set: function (value) {
  18334. var keyboard = this.inputs.attached["keyboard"];
  18335. if (keyboard)
  18336. keyboard.keysLeft = value;
  18337. },
  18338. enumerable: true,
  18339. configurable: true
  18340. });
  18341. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  18342. get: function () {
  18343. var keyboard = this.inputs.attached["keyboard"];
  18344. if (keyboard)
  18345. return keyboard.keysRight;
  18346. },
  18347. set: function (value) {
  18348. var keyboard = this.inputs.attached["keyboard"];
  18349. if (keyboard)
  18350. keyboard.keysRight = value;
  18351. },
  18352. enumerable: true,
  18353. configurable: true
  18354. });
  18355. // Controls
  18356. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  18357. this.inputs.attachElement(element, noPreventDefault);
  18358. };
  18359. FreeCamera.prototype.detachControl = function (element) {
  18360. this.inputs.detachElement(element);
  18361. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  18362. this.cameraRotation = new BABYLON.Vector2(0, 0);
  18363. };
  18364. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  18365. get: function () {
  18366. return this._collisionMask;
  18367. },
  18368. set: function (mask) {
  18369. this._collisionMask = !isNaN(mask) ? mask : -1;
  18370. },
  18371. enumerable: true,
  18372. configurable: true
  18373. });
  18374. FreeCamera.prototype._collideWithWorld = function (velocity) {
  18375. var globalPosition;
  18376. if (this.parent) {
  18377. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  18378. }
  18379. else {
  18380. globalPosition = this.position;
  18381. }
  18382. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  18383. this._collider.radius = this.ellipsoid;
  18384. this._collider.collisionMask = this._collisionMask;
  18385. //no need for clone, as long as gravity is not on.
  18386. var actualVelocity = velocity;
  18387. //add gravity to the velocity to prevent the dual-collision checking
  18388. if (this.applyGravity) {
  18389. //this prevents mending with cameraDirection, a global variable of the free camera class.
  18390. actualVelocity = velocity.add(this.getScene().gravity);
  18391. }
  18392. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  18393. };
  18394. FreeCamera.prototype._checkInputs = function () {
  18395. if (!this._localDirection) {
  18396. this._localDirection = BABYLON.Vector3.Zero();
  18397. this._transformedDirection = BABYLON.Vector3.Zero();
  18398. }
  18399. this.inputs.checkInputs();
  18400. _super.prototype._checkInputs.call(this);
  18401. };
  18402. FreeCamera.prototype._decideIfNeedsToMove = function () {
  18403. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  18404. };
  18405. FreeCamera.prototype._updatePosition = function () {
  18406. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  18407. this._collideWithWorld(this.cameraDirection);
  18408. }
  18409. else {
  18410. _super.prototype._updatePosition.call(this);
  18411. }
  18412. };
  18413. FreeCamera.prototype.dispose = function () {
  18414. this.inputs.clear();
  18415. _super.prototype.dispose.call(this);
  18416. };
  18417. FreeCamera.prototype.getClassName = function () {
  18418. return "FreeCamera";
  18419. };
  18420. return FreeCamera;
  18421. }(BABYLON.TargetCamera));
  18422. __decorate([
  18423. BABYLON.serializeAsVector3()
  18424. ], FreeCamera.prototype, "ellipsoid", void 0);
  18425. __decorate([
  18426. BABYLON.serialize()
  18427. ], FreeCamera.prototype, "checkCollisions", void 0);
  18428. __decorate([
  18429. BABYLON.serialize()
  18430. ], FreeCamera.prototype, "applyGravity", void 0);
  18431. BABYLON.FreeCamera = FreeCamera;
  18432. })(BABYLON || (BABYLON = {}));
  18433. //# sourceMappingURL=babylon.freeCamera.js.map
  18434. var BABYLON;
  18435. (function (BABYLON) {
  18436. var FreeCameraInputsManager = (function (_super) {
  18437. __extends(FreeCameraInputsManager, _super);
  18438. function FreeCameraInputsManager(camera) {
  18439. return _super.call(this, camera) || this;
  18440. }
  18441. FreeCameraInputsManager.prototype.addKeyboard = function () {
  18442. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  18443. return this;
  18444. };
  18445. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  18446. if (touchEnabled === void 0) { touchEnabled = true; }
  18447. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  18448. return this;
  18449. };
  18450. FreeCameraInputsManager.prototype.addGamepad = function () {
  18451. this.add(new BABYLON.FreeCameraGamepadInput());
  18452. return this;
  18453. };
  18454. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  18455. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  18456. return this;
  18457. };
  18458. FreeCameraInputsManager.prototype.addTouch = function () {
  18459. this.add(new BABYLON.FreeCameraTouchInput());
  18460. return this;
  18461. };
  18462. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  18463. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  18464. return this;
  18465. };
  18466. return FreeCameraInputsManager;
  18467. }(BABYLON.CameraInputsManager));
  18468. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  18469. })(BABYLON || (BABYLON = {}));
  18470. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  18471. /// <reference path="babylon.targetCamera.ts" />
  18472. var BABYLON;
  18473. (function (BABYLON) {
  18474. var FollowCamera = (function (_super) {
  18475. __extends(FollowCamera, _super);
  18476. function FollowCamera(name, position, scene, lockedTarget) {
  18477. var _this = _super.call(this, name, position, scene) || this;
  18478. _this.radius = 12;
  18479. _this.rotationOffset = 0;
  18480. _this.heightOffset = 4;
  18481. _this.cameraAcceleration = 0.05;
  18482. _this.maxCameraSpeed = 20;
  18483. _this.lockedTarget = lockedTarget;
  18484. return _this;
  18485. }
  18486. FollowCamera.prototype.getRadians = function (degrees) {
  18487. return degrees * Math.PI / 180;
  18488. };
  18489. FollowCamera.prototype.follow = function (cameraTarget) {
  18490. if (!cameraTarget)
  18491. return;
  18492. var yRotation;
  18493. if (cameraTarget.rotationQuaternion) {
  18494. var rotMatrix = new BABYLON.Matrix();
  18495. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  18496. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  18497. }
  18498. else {
  18499. yRotation = cameraTarget.rotation.y;
  18500. }
  18501. var radians = this.getRadians(this.rotationOffset) + yRotation;
  18502. var targetPosition = cameraTarget.getAbsolutePosition();
  18503. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  18504. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  18505. var dx = targetX - this.position.x;
  18506. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  18507. var dz = (targetZ) - this.position.z;
  18508. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  18509. var vy = dy * this.cameraAcceleration;
  18510. var vz = dz * this.cameraAcceleration * 2;
  18511. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  18512. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18513. }
  18514. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  18515. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18516. }
  18517. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  18518. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18519. }
  18520. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  18521. this.setTarget(targetPosition);
  18522. };
  18523. FollowCamera.prototype._checkInputs = function () {
  18524. _super.prototype._checkInputs.call(this);
  18525. this.follow(this.lockedTarget);
  18526. };
  18527. FollowCamera.prototype.getClassName = function () {
  18528. return "FollowCamera";
  18529. };
  18530. return FollowCamera;
  18531. }(BABYLON.TargetCamera));
  18532. __decorate([
  18533. BABYLON.serialize()
  18534. ], FollowCamera.prototype, "radius", void 0);
  18535. __decorate([
  18536. BABYLON.serialize()
  18537. ], FollowCamera.prototype, "rotationOffset", void 0);
  18538. __decorate([
  18539. BABYLON.serialize()
  18540. ], FollowCamera.prototype, "heightOffset", void 0);
  18541. __decorate([
  18542. BABYLON.serialize()
  18543. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  18544. __decorate([
  18545. BABYLON.serialize()
  18546. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  18547. __decorate([
  18548. BABYLON.serializeAsMeshReference("lockedTargetId")
  18549. ], FollowCamera.prototype, "lockedTarget", void 0);
  18550. BABYLON.FollowCamera = FollowCamera;
  18551. var ArcFollowCamera = (function (_super) {
  18552. __extends(ArcFollowCamera, _super);
  18553. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  18554. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  18555. _this.alpha = alpha;
  18556. _this.beta = beta;
  18557. _this.radius = radius;
  18558. _this.target = target;
  18559. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  18560. _this.follow();
  18561. return _this;
  18562. }
  18563. ArcFollowCamera.prototype.follow = function () {
  18564. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  18565. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  18566. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  18567. var targetPosition = this.target.getAbsolutePosition();
  18568. this.position = targetPosition.add(this._cartesianCoordinates);
  18569. this.setTarget(targetPosition);
  18570. };
  18571. ArcFollowCamera.prototype._checkInputs = function () {
  18572. _super.prototype._checkInputs.call(this);
  18573. this.follow();
  18574. };
  18575. ArcFollowCamera.prototype.getClassName = function () {
  18576. return "ArcFollowCamera";
  18577. };
  18578. return ArcFollowCamera;
  18579. }(BABYLON.TargetCamera));
  18580. BABYLON.ArcFollowCamera = ArcFollowCamera;
  18581. })(BABYLON || (BABYLON = {}));
  18582. //# sourceMappingURL=babylon.followCamera.js.map
  18583. /// <reference path="babylon.freeCamera.ts" />
  18584. var BABYLON;
  18585. (function (BABYLON) {
  18586. // We're mainly based on the logic defined into the FreeCamera code
  18587. var TouchCamera = (function (_super) {
  18588. __extends(TouchCamera, _super);
  18589. //-- end properties for backward compatibility for inputs
  18590. function TouchCamera(name, position, scene) {
  18591. var _this = _super.call(this, name, position, scene) || this;
  18592. _this.inputs.addTouch();
  18593. _this._setupInputs();
  18594. return _this;
  18595. }
  18596. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  18597. //-- Begin properties for backward compatibility for inputs
  18598. get: function () {
  18599. var touch = this.inputs.attached["touch"];
  18600. if (touch)
  18601. return touch.touchAngularSensibility;
  18602. },
  18603. set: function (value) {
  18604. var touch = this.inputs.attached["touch"];
  18605. if (touch)
  18606. touch.touchAngularSensibility = value;
  18607. },
  18608. enumerable: true,
  18609. configurable: true
  18610. });
  18611. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  18612. get: function () {
  18613. var touch = this.inputs.attached["touch"];
  18614. if (touch)
  18615. return touch.touchMoveSensibility;
  18616. },
  18617. set: function (value) {
  18618. var touch = this.inputs.attached["touch"];
  18619. if (touch)
  18620. touch.touchMoveSensibility = value;
  18621. },
  18622. enumerable: true,
  18623. configurable: true
  18624. });
  18625. TouchCamera.prototype.getClassName = function () {
  18626. return "TouchCamera";
  18627. };
  18628. TouchCamera.prototype._setupInputs = function () {
  18629. var mouse = this.inputs.attached["mouse"];
  18630. if (mouse) {
  18631. mouse.touchEnabled = false;
  18632. }
  18633. };
  18634. return TouchCamera;
  18635. }(BABYLON.FreeCamera));
  18636. BABYLON.TouchCamera = TouchCamera;
  18637. })(BABYLON || (BABYLON = {}));
  18638. //# sourceMappingURL=babylon.touchCamera.js.map
  18639. /// <reference path="babylon.targetCamera.ts" />
  18640. /// <reference path="..\Tools\babylon.tools.ts" />
  18641. var BABYLON;
  18642. (function (BABYLON) {
  18643. var ArcRotateCamera = (function (_super) {
  18644. __extends(ArcRotateCamera, _super);
  18645. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  18646. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  18647. _this.inertialAlphaOffset = 0;
  18648. _this.inertialBetaOffset = 0;
  18649. _this.inertialRadiusOffset = 0;
  18650. _this.lowerAlphaLimit = null;
  18651. _this.upperAlphaLimit = null;
  18652. _this.lowerBetaLimit = 0.01;
  18653. _this.upperBetaLimit = Math.PI;
  18654. _this.lowerRadiusLimit = null;
  18655. _this.upperRadiusLimit = null;
  18656. _this.inertialPanningX = 0;
  18657. _this.inertialPanningY = 0;
  18658. //-- end properties for backward compatibility for inputs
  18659. _this.zoomOnFactor = 1;
  18660. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  18661. _this.allowUpsideDown = true;
  18662. _this._viewMatrix = new BABYLON.Matrix();
  18663. // Panning
  18664. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  18665. _this.checkCollisions = false;
  18666. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  18667. _this._collider = new BABYLON.Collider();
  18668. _this._previousPosition = BABYLON.Vector3.Zero();
  18669. _this._collisionVelocity = BABYLON.Vector3.Zero();
  18670. _this._newPosition = BABYLON.Vector3.Zero();
  18671. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  18672. if (collidedMesh === void 0) { collidedMesh = null; }
  18673. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  18674. newPosition.multiplyInPlace(_this._collider.radius);
  18675. }
  18676. if (!collidedMesh) {
  18677. _this._previousPosition.copyFrom(_this.position);
  18678. }
  18679. else {
  18680. _this.setPosition(newPosition);
  18681. if (_this.onCollide) {
  18682. _this.onCollide(collidedMesh);
  18683. }
  18684. }
  18685. // Recompute because of constraints
  18686. var cosa = Math.cos(_this.alpha);
  18687. var sina = Math.sin(_this.alpha);
  18688. var cosb = Math.cos(_this.beta);
  18689. var sinb = Math.sin(_this.beta);
  18690. if (sinb === 0) {
  18691. sinb = 0.0001;
  18692. }
  18693. var target = _this._getTargetPosition();
  18694. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  18695. _this.position.copyFrom(_this._newPosition);
  18696. var up = _this.upVector;
  18697. if (_this.allowUpsideDown && _this.beta < 0) {
  18698. up = up.clone();
  18699. up = up.negate();
  18700. }
  18701. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  18702. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  18703. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  18704. _this._collisionTriggered = false;
  18705. };
  18706. if (!target) {
  18707. _this.target = BABYLON.Vector3.Zero();
  18708. }
  18709. else {
  18710. _this.target = target;
  18711. }
  18712. _this.alpha = alpha;
  18713. _this.beta = beta;
  18714. _this.radius = radius;
  18715. _this.getViewMatrix();
  18716. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  18717. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  18718. return _this;
  18719. }
  18720. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  18721. //-- begin properties for backward compatibility for inputs
  18722. get: function () {
  18723. var pointers = this.inputs.attached["pointers"];
  18724. if (pointers)
  18725. return pointers.angularSensibilityX;
  18726. },
  18727. set: function (value) {
  18728. var pointers = this.inputs.attached["pointers"];
  18729. if (pointers) {
  18730. pointers.angularSensibilityX = value;
  18731. }
  18732. },
  18733. enumerable: true,
  18734. configurable: true
  18735. });
  18736. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  18737. get: function () {
  18738. var pointers = this.inputs.attached["pointers"];
  18739. if (pointers)
  18740. return pointers.angularSensibilityY;
  18741. },
  18742. set: function (value) {
  18743. var pointers = this.inputs.attached["pointers"];
  18744. if (pointers) {
  18745. pointers.angularSensibilityY = value;
  18746. }
  18747. },
  18748. enumerable: true,
  18749. configurable: true
  18750. });
  18751. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  18752. get: function () {
  18753. var pointers = this.inputs.attached["pointers"];
  18754. if (pointers)
  18755. return pointers.pinchPrecision;
  18756. },
  18757. set: function (value) {
  18758. var pointers = this.inputs.attached["pointers"];
  18759. if (pointers) {
  18760. pointers.pinchPrecision = value;
  18761. }
  18762. },
  18763. enumerable: true,
  18764. configurable: true
  18765. });
  18766. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  18767. get: function () {
  18768. var pointers = this.inputs.attached["pointers"];
  18769. if (pointers)
  18770. return pointers.panningSensibility;
  18771. },
  18772. set: function (value) {
  18773. var pointers = this.inputs.attached["pointers"];
  18774. if (pointers) {
  18775. pointers.panningSensibility = value;
  18776. }
  18777. },
  18778. enumerable: true,
  18779. configurable: true
  18780. });
  18781. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  18782. get: function () {
  18783. var keyboard = this.inputs.attached["keyboard"];
  18784. if (keyboard)
  18785. return keyboard.keysUp;
  18786. },
  18787. set: function (value) {
  18788. var keyboard = this.inputs.attached["keyboard"];
  18789. if (keyboard)
  18790. keyboard.keysUp = value;
  18791. },
  18792. enumerable: true,
  18793. configurable: true
  18794. });
  18795. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  18796. get: function () {
  18797. var keyboard = this.inputs.attached["keyboard"];
  18798. if (keyboard)
  18799. return keyboard.keysDown;
  18800. },
  18801. set: function (value) {
  18802. var keyboard = this.inputs.attached["keyboard"];
  18803. if (keyboard)
  18804. keyboard.keysDown = value;
  18805. },
  18806. enumerable: true,
  18807. configurable: true
  18808. });
  18809. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  18810. get: function () {
  18811. var keyboard = this.inputs.attached["keyboard"];
  18812. if (keyboard)
  18813. return keyboard.keysLeft;
  18814. },
  18815. set: function (value) {
  18816. var keyboard = this.inputs.attached["keyboard"];
  18817. if (keyboard)
  18818. keyboard.keysLeft = value;
  18819. },
  18820. enumerable: true,
  18821. configurable: true
  18822. });
  18823. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  18824. get: function () {
  18825. var keyboard = this.inputs.attached["keyboard"];
  18826. if (keyboard)
  18827. return keyboard.keysRight;
  18828. },
  18829. set: function (value) {
  18830. var keyboard = this.inputs.attached["keyboard"];
  18831. if (keyboard)
  18832. keyboard.keysRight = value;
  18833. },
  18834. enumerable: true,
  18835. configurable: true
  18836. });
  18837. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  18838. get: function () {
  18839. var mousewheel = this.inputs.attached["mousewheel"];
  18840. if (mousewheel)
  18841. return mousewheel.wheelPrecision;
  18842. },
  18843. set: function (value) {
  18844. var mousewheel = this.inputs.attached["mousewheel"];
  18845. if (mousewheel)
  18846. mousewheel.wheelPrecision = value;
  18847. },
  18848. enumerable: true,
  18849. configurable: true
  18850. });
  18851. // Cache
  18852. ArcRotateCamera.prototype._initCache = function () {
  18853. _super.prototype._initCache.call(this);
  18854. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18855. this._cache.alpha = undefined;
  18856. this._cache.beta = undefined;
  18857. this._cache.radius = undefined;
  18858. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  18859. };
  18860. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  18861. if (!ignoreParentClass) {
  18862. _super.prototype._updateCache.call(this);
  18863. }
  18864. this._cache.target.copyFrom(this._getTargetPosition());
  18865. this._cache.alpha = this.alpha;
  18866. this._cache.beta = this.beta;
  18867. this._cache.radius = this.radius;
  18868. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  18869. };
  18870. ArcRotateCamera.prototype._getTargetPosition = function () {
  18871. if (this.target.getAbsolutePosition) {
  18872. var pos = this.target.getAbsolutePosition();
  18873. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  18874. }
  18875. return this.target;
  18876. };
  18877. // Synchronized
  18878. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  18879. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  18880. return false;
  18881. return this._cache.target.equals(this.target)
  18882. && this._cache.alpha === this.alpha
  18883. && this._cache.beta === this.beta
  18884. && this._cache.radius === this.radius
  18885. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  18886. };
  18887. // Methods
  18888. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  18889. var _this = this;
  18890. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  18891. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  18892. this._useCtrlForPanning = useCtrlForPanning;
  18893. this._panningMouseButton = panningMouseButton;
  18894. this.inputs.attachElement(element, noPreventDefault);
  18895. this._reset = function () {
  18896. _this.inertialAlphaOffset = 0;
  18897. _this.inertialBetaOffset = 0;
  18898. _this.inertialRadiusOffset = 0;
  18899. };
  18900. };
  18901. ArcRotateCamera.prototype.detachControl = function (element) {
  18902. this.inputs.detachElement(element);
  18903. if (this._reset) {
  18904. this._reset();
  18905. }
  18906. };
  18907. ArcRotateCamera.prototype._checkInputs = function () {
  18908. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  18909. if (this._collisionTriggered) {
  18910. return;
  18911. }
  18912. this.inputs.checkInputs();
  18913. // Inertia
  18914. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  18915. if (this.getScene().useRightHandedSystem) {
  18916. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18917. }
  18918. else {
  18919. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18920. }
  18921. this.beta += this.inertialBetaOffset;
  18922. this.radius -= this.inertialRadiusOffset;
  18923. this.inertialAlphaOffset *= this.inertia;
  18924. this.inertialBetaOffset *= this.inertia;
  18925. this.inertialRadiusOffset *= this.inertia;
  18926. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  18927. this.inertialAlphaOffset = 0;
  18928. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  18929. this.inertialBetaOffset = 0;
  18930. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  18931. this.inertialRadiusOffset = 0;
  18932. }
  18933. // Panning inertia
  18934. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  18935. if (!this._localDirection) {
  18936. this._localDirection = BABYLON.Vector3.Zero();
  18937. this._transformedDirection = BABYLON.Vector3.Zero();
  18938. }
  18939. this.inertialPanningX *= this.inertia;
  18940. this.inertialPanningY *= this.inertia;
  18941. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  18942. this.inertialPanningX = 0;
  18943. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  18944. this.inertialPanningY = 0;
  18945. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  18946. this._localDirection.multiplyInPlace(this.panningAxis);
  18947. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  18948. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  18949. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  18950. if (!this.panningAxis.y) {
  18951. this._transformedDirection.y = 0;
  18952. }
  18953. if (!this.target.getAbsolutePosition) {
  18954. this.target.addInPlace(this._transformedDirection);
  18955. }
  18956. }
  18957. // Limits
  18958. this._checkLimits();
  18959. _super.prototype._checkInputs.call(this);
  18960. };
  18961. ArcRotateCamera.prototype._checkLimits = function () {
  18962. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  18963. if (this.allowUpsideDown && this.beta > Math.PI) {
  18964. this.beta = this.beta - (2 * Math.PI);
  18965. }
  18966. }
  18967. else {
  18968. if (this.beta < this.lowerBetaLimit) {
  18969. this.beta = this.lowerBetaLimit;
  18970. }
  18971. }
  18972. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  18973. if (this.allowUpsideDown && this.beta < -Math.PI) {
  18974. this.beta = this.beta + (2 * Math.PI);
  18975. }
  18976. }
  18977. else {
  18978. if (this.beta > this.upperBetaLimit) {
  18979. this.beta = this.upperBetaLimit;
  18980. }
  18981. }
  18982. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  18983. this.alpha = this.lowerAlphaLimit;
  18984. }
  18985. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  18986. this.alpha = this.upperAlphaLimit;
  18987. }
  18988. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  18989. this.radius = this.lowerRadiusLimit;
  18990. }
  18991. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  18992. this.radius = this.upperRadiusLimit;
  18993. }
  18994. };
  18995. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  18996. var radiusv3 = this.position.subtract(this._getTargetPosition());
  18997. this.radius = radiusv3.length();
  18998. // Alpha
  18999. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  19000. if (radiusv3.z < 0) {
  19001. this.alpha = 2 * Math.PI - this.alpha;
  19002. }
  19003. // Beta
  19004. this.beta = Math.acos(radiusv3.y / this.radius);
  19005. this._checkLimits();
  19006. };
  19007. ArcRotateCamera.prototype.setPosition = function (position) {
  19008. if (this.position.equals(position)) {
  19009. return;
  19010. }
  19011. this.position.copyFrom(position);
  19012. this.rebuildAnglesAndRadius();
  19013. };
  19014. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  19015. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  19016. if (allowSamePosition === void 0) { allowSamePosition = false; }
  19017. if (!allowSamePosition && this._getTargetPosition().equals(target)) {
  19018. return;
  19019. }
  19020. if (toBoundingCenter && target.getBoundingInfo) {
  19021. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  19022. }
  19023. else {
  19024. this._targetBoundingCenter = null;
  19025. }
  19026. this.target = target;
  19027. this.rebuildAnglesAndRadius();
  19028. };
  19029. ArcRotateCamera.prototype._getViewMatrix = function () {
  19030. // Compute
  19031. var cosa = Math.cos(this.alpha);
  19032. var sina = Math.sin(this.alpha);
  19033. var cosb = Math.cos(this.beta);
  19034. var sinb = Math.sin(this.beta);
  19035. if (sinb === 0) {
  19036. sinb = 0.0001;
  19037. }
  19038. var target = this._getTargetPosition();
  19039. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  19040. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  19041. this._collider.radius = this.collisionRadius;
  19042. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  19043. this._collisionTriggered = true;
  19044. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  19045. }
  19046. else {
  19047. this.position.copyFrom(this._newPosition);
  19048. var up = this.upVector;
  19049. if (this.allowUpsideDown && sinb < 0) {
  19050. up = up.clone();
  19051. up = up.negate();
  19052. }
  19053. if (this.getScene().useRightHandedSystem) {
  19054. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  19055. }
  19056. else {
  19057. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  19058. }
  19059. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  19060. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  19061. }
  19062. this._currentTarget = target;
  19063. return this._viewMatrix;
  19064. };
  19065. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  19066. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  19067. meshes = meshes || this.getScene().meshes;
  19068. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  19069. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  19070. this.radius = distance * this.zoomOnFactor;
  19071. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  19072. };
  19073. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  19074. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  19075. var meshesOrMinMaxVector;
  19076. var distance;
  19077. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  19078. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  19079. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  19080. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  19081. }
  19082. else {
  19083. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  19084. distance = meshesOrMinMaxVectorAndDistance.distance;
  19085. }
  19086. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  19087. if (!doNotUpdateMaxZ) {
  19088. this.maxZ = distance * 2;
  19089. }
  19090. };
  19091. /**
  19092. * @override
  19093. * Override Camera.createRigCamera
  19094. */
  19095. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  19096. var alphaShift;
  19097. switch (this.cameraRigMode) {
  19098. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19099. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19100. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19101. case BABYLON.Camera.RIG_MODE_VR:
  19102. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  19103. break;
  19104. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19105. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  19106. break;
  19107. }
  19108. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  19109. rigCam._cameraRigParams = {};
  19110. return rigCam;
  19111. };
  19112. /**
  19113. * @override
  19114. * Override Camera._updateRigCameras
  19115. */
  19116. ArcRotateCamera.prototype._updateRigCameras = function () {
  19117. var camLeft = this._rigCameras[0];
  19118. var camRight = this._rigCameras[1];
  19119. camLeft.beta = camRight.beta = this.beta;
  19120. camLeft.radius = camRight.radius = this.radius;
  19121. switch (this.cameraRigMode) {
  19122. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19123. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19124. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19125. case BABYLON.Camera.RIG_MODE_VR:
  19126. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  19127. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  19128. break;
  19129. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19130. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  19131. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  19132. break;
  19133. }
  19134. _super.prototype._updateRigCameras.call(this);
  19135. };
  19136. ArcRotateCamera.prototype.dispose = function () {
  19137. this.inputs.clear();
  19138. _super.prototype.dispose.call(this);
  19139. };
  19140. ArcRotateCamera.prototype.getClassName = function () {
  19141. return "ArcRotateCamera";
  19142. };
  19143. return ArcRotateCamera;
  19144. }(BABYLON.TargetCamera));
  19145. __decorate([
  19146. BABYLON.serialize()
  19147. ], ArcRotateCamera.prototype, "alpha", void 0);
  19148. __decorate([
  19149. BABYLON.serialize()
  19150. ], ArcRotateCamera.prototype, "beta", void 0);
  19151. __decorate([
  19152. BABYLON.serialize()
  19153. ], ArcRotateCamera.prototype, "radius", void 0);
  19154. __decorate([
  19155. BABYLON.serializeAsVector3()
  19156. ], ArcRotateCamera.prototype, "target", void 0);
  19157. __decorate([
  19158. BABYLON.serialize()
  19159. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  19160. __decorate([
  19161. BABYLON.serialize()
  19162. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  19163. __decorate([
  19164. BABYLON.serialize()
  19165. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  19166. __decorate([
  19167. BABYLON.serialize()
  19168. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  19169. __decorate([
  19170. BABYLON.serialize()
  19171. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  19172. __decorate([
  19173. BABYLON.serialize()
  19174. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  19175. __decorate([
  19176. BABYLON.serialize()
  19177. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  19178. __decorate([
  19179. BABYLON.serialize()
  19180. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  19181. __decorate([
  19182. BABYLON.serialize()
  19183. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  19184. __decorate([
  19185. BABYLON.serialize()
  19186. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  19187. __decorate([
  19188. BABYLON.serialize()
  19189. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  19190. __decorate([
  19191. BABYLON.serialize()
  19192. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  19193. __decorate([
  19194. BABYLON.serialize()
  19195. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  19196. BABYLON.ArcRotateCamera = ArcRotateCamera;
  19197. })(BABYLON || (BABYLON = {}));
  19198. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  19199. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  19200. var BABYLON;
  19201. (function (BABYLON) {
  19202. var ArcRotateCameraInputsManager = (function (_super) {
  19203. __extends(ArcRotateCameraInputsManager, _super);
  19204. function ArcRotateCameraInputsManager(camera) {
  19205. return _super.call(this, camera) || this;
  19206. }
  19207. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  19208. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  19209. return this;
  19210. };
  19211. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  19212. this.add(new BABYLON.ArcRotateCameraPointersInput());
  19213. return this;
  19214. };
  19215. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  19216. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  19217. return this;
  19218. };
  19219. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  19220. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  19221. return this;
  19222. };
  19223. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  19224. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  19225. return this;
  19226. };
  19227. return ArcRotateCameraInputsManager;
  19228. }(BABYLON.CameraInputsManager));
  19229. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  19230. })(BABYLON || (BABYLON = {}));
  19231. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  19232. var BABYLON;
  19233. (function (BABYLON) {
  19234. var RenderingManager = (function () {
  19235. function RenderingManager(scene) {
  19236. this._renderingGroups = new Array();
  19237. this._autoClearDepthStencil = {};
  19238. this._customOpaqueSortCompareFn = {};
  19239. this._customAlphaTestSortCompareFn = {};
  19240. this._customTransparentSortCompareFn = {};
  19241. this._renderinGroupInfo = null;
  19242. this._scene = scene;
  19243. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  19244. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  19245. }
  19246. }
  19247. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  19248. if (depth === void 0) { depth = true; }
  19249. if (stencil === void 0) { stencil = true; }
  19250. if (this._depthStencilBufferAlreadyCleaned) {
  19251. return;
  19252. }
  19253. this._scene.getEngine().clear(null, false, depth, stencil);
  19254. this._depthStencilBufferAlreadyCleaned = true;
  19255. };
  19256. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  19257. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  19258. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  19259. var info = null;
  19260. if (observable) {
  19261. if (!this._renderinGroupInfo) {
  19262. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  19263. }
  19264. info = this._renderinGroupInfo;
  19265. info.scene = this._scene;
  19266. info.camera = this._scene.activeCamera;
  19267. }
  19268. // Dispatch sprites
  19269. if (renderSprites) {
  19270. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  19271. var manager = this._scene.spriteManagers[index];
  19272. this.dispatchSprites(manager);
  19273. }
  19274. }
  19275. // Render
  19276. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19277. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  19278. var renderingGroup = this._renderingGroups[index];
  19279. if (!renderingGroup && !observable)
  19280. continue;
  19281. this._currentIndex = index;
  19282. var renderingGroupMask = 0;
  19283. // Fire PRECLEAR stage
  19284. if (observable) {
  19285. renderingGroupMask = Math.pow(2, index);
  19286. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  19287. info.renderingGroupId = index;
  19288. observable.notifyObservers(info, renderingGroupMask);
  19289. }
  19290. // Clear depth/stencil if needed
  19291. var autoClear = this._autoClearDepthStencil[index];
  19292. if (autoClear && autoClear.autoClear) {
  19293. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  19294. }
  19295. if (observable) {
  19296. // Fire PREOPAQUE stage
  19297. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  19298. observable.notifyObservers(info, renderingGroupMask);
  19299. // Fire PRETRANSPARENT stage
  19300. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  19301. observable.notifyObservers(info, renderingGroupMask);
  19302. }
  19303. if (renderingGroup)
  19304. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  19305. // Fire POSTTRANSPARENT stage
  19306. if (observable) {
  19307. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  19308. observable.notifyObservers(info, renderingGroupMask);
  19309. }
  19310. }
  19311. };
  19312. RenderingManager.prototype.reset = function () {
  19313. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19314. var renderingGroup = this._renderingGroups[index];
  19315. if (renderingGroup) {
  19316. renderingGroup.prepare();
  19317. }
  19318. }
  19319. };
  19320. RenderingManager.prototype.dispose = function () {
  19321. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19322. var renderingGroup = this._renderingGroups[index];
  19323. if (renderingGroup) {
  19324. renderingGroup.dispose();
  19325. }
  19326. }
  19327. this._renderingGroups.length = 0;
  19328. };
  19329. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  19330. if (!this._renderingGroups[renderingGroupId]) {
  19331. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  19332. }
  19333. };
  19334. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  19335. var renderingGroupId = spriteManager.renderingGroupId || 0;
  19336. this._prepareRenderingGroup(renderingGroupId);
  19337. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  19338. };
  19339. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  19340. var renderingGroupId = particleSystem.renderingGroupId || 0;
  19341. this._prepareRenderingGroup(renderingGroupId);
  19342. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  19343. };
  19344. RenderingManager.prototype.dispatch = function (subMesh) {
  19345. var mesh = subMesh.getMesh();
  19346. var renderingGroupId = mesh.renderingGroupId || 0;
  19347. this._prepareRenderingGroup(renderingGroupId);
  19348. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  19349. };
  19350. /**
  19351. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19352. * This allowed control for front to back rendering or reversly depending of the special needs.
  19353. *
  19354. * @param renderingGroupId The rendering group id corresponding to its index
  19355. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19356. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19357. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19358. */
  19359. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19360. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19361. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19362. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19363. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  19364. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  19365. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  19366. if (this._renderingGroups[renderingGroupId]) {
  19367. var group = this._renderingGroups[renderingGroupId];
  19368. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  19369. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  19370. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  19371. }
  19372. };
  19373. /**
  19374. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19375. *
  19376. * @param renderingGroupId The rendering group id corresponding to its index
  19377. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19378. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19379. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19380. */
  19381. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19382. if (depth === void 0) { depth = true; }
  19383. if (stencil === void 0) { stencil = true; }
  19384. this._autoClearDepthStencil[renderingGroupId] = {
  19385. autoClear: autoClearDepthStencil,
  19386. depth: depth,
  19387. stencil: stencil
  19388. };
  19389. };
  19390. return RenderingManager;
  19391. }());
  19392. /**
  19393. * The max id used for rendering groups (not included)
  19394. */
  19395. RenderingManager.MAX_RENDERINGGROUPS = 4;
  19396. /**
  19397. * The min id used for rendering groups (included)
  19398. */
  19399. RenderingManager.MIN_RENDERINGGROUPS = 0;
  19400. BABYLON.RenderingManager = RenderingManager;
  19401. })(BABYLON || (BABYLON = {}));
  19402. //# sourceMappingURL=babylon.renderingManager.js.map
  19403. var BABYLON;
  19404. (function (BABYLON) {
  19405. var RenderingGroup = (function () {
  19406. /**
  19407. * Creates a new rendering group.
  19408. * @param index The rendering group index
  19409. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  19410. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  19411. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  19412. */
  19413. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19414. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19415. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19416. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19417. this.index = index;
  19418. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  19419. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  19420. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  19421. this._particleSystems = new BABYLON.SmartArray(256);
  19422. this._spriteManagers = new BABYLON.SmartArray(256);
  19423. this._scene = scene;
  19424. this.opaqueSortCompareFn = opaqueSortCompareFn;
  19425. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  19426. this.transparentSortCompareFn = transparentSortCompareFn;
  19427. }
  19428. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  19429. /**
  19430. * Set the opaque sort comparison function.
  19431. * If null the sub meshes will be render in the order they were created
  19432. */
  19433. set: function (value) {
  19434. this._opaqueSortCompareFn = value;
  19435. if (value) {
  19436. this._renderOpaque = this.renderOpaqueSorted;
  19437. }
  19438. else {
  19439. this._renderOpaque = RenderingGroup.renderUnsorted;
  19440. }
  19441. },
  19442. enumerable: true,
  19443. configurable: true
  19444. });
  19445. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19446. /**
  19447. * Set the alpha test sort comparison function.
  19448. * If null the sub meshes will be render in the order they were created
  19449. */
  19450. set: function (value) {
  19451. this._alphaTestSortCompareFn = value;
  19452. if (value) {
  19453. this._renderAlphaTest = this.renderAlphaTestSorted;
  19454. }
  19455. else {
  19456. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19457. }
  19458. },
  19459. enumerable: true,
  19460. configurable: true
  19461. });
  19462. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19463. /**
  19464. * Set the transparent sort comparison function.
  19465. * If null the sub meshes will be render in the order they were created
  19466. */
  19467. set: function (value) {
  19468. if (value) {
  19469. this._transparentSortCompareFn = value;
  19470. }
  19471. else {
  19472. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19473. }
  19474. this._renderTransparent = this.renderTransparentSorted;
  19475. },
  19476. enumerable: true,
  19477. configurable: true
  19478. });
  19479. /**
  19480. * Render all the sub meshes contained in the group.
  19481. * @param customRenderFunction Used to override the default render behaviour of the group.
  19482. * @returns true if rendered some submeshes.
  19483. */
  19484. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19485. if (customRenderFunction) {
  19486. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  19487. return;
  19488. }
  19489. var engine = this._scene.getEngine();
  19490. // Opaque
  19491. if (this._opaqueSubMeshes.length !== 0) {
  19492. this._renderOpaque(this._opaqueSubMeshes);
  19493. }
  19494. // Alpha test
  19495. if (this._alphaTestSubMeshes.length !== 0) {
  19496. engine.setAlphaTesting(true);
  19497. this._renderAlphaTest(this._alphaTestSubMeshes);
  19498. engine.setAlphaTesting(false);
  19499. }
  19500. var stencilState = engine.getStencilBuffer();
  19501. engine.setStencilBuffer(false);
  19502. // Sprites
  19503. if (renderSprites) {
  19504. this._renderSprites();
  19505. }
  19506. // Particles
  19507. if (renderParticles) {
  19508. this._renderParticles(activeMeshes);
  19509. }
  19510. if (this.onBeforeTransparentRendering) {
  19511. this.onBeforeTransparentRendering();
  19512. }
  19513. // Transparent
  19514. if (this._transparentSubMeshes.length !== 0) {
  19515. this._renderTransparent(this._transparentSubMeshes);
  19516. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19517. }
  19518. engine.setStencilBuffer(stencilState);
  19519. };
  19520. /**
  19521. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19522. * @param subMeshes The submeshes to render
  19523. */
  19524. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19525. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  19526. };
  19527. /**
  19528. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19529. * @param subMeshes The submeshes to render
  19530. */
  19531. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19532. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  19533. };
  19534. /**
  19535. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19536. * @param subMeshes The submeshes to render
  19537. */
  19538. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19539. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  19540. };
  19541. /**
  19542. * Renders the submeshes in a specified order.
  19543. * @param subMeshes The submeshes to sort before render
  19544. * @param sortCompareFn The comparison function use to sort
  19545. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19546. * @param transparent Specifies to activate blending if true
  19547. */
  19548. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  19549. var subIndex = 0;
  19550. var subMesh;
  19551. for (; subIndex < subMeshes.length; subIndex++) {
  19552. subMesh = subMeshes.data[subIndex];
  19553. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19554. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19555. }
  19556. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19557. sortedArray.sort(sortCompareFn);
  19558. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19559. subMesh = sortedArray[subIndex];
  19560. subMesh.render(transparent);
  19561. }
  19562. };
  19563. /**
  19564. * Renders the submeshes in the order they were dispatched (no sort applied).
  19565. * @param subMeshes The submeshes to render
  19566. */
  19567. RenderingGroup.renderUnsorted = function (subMeshes) {
  19568. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19569. var submesh = subMeshes.data[subIndex];
  19570. submesh.render(false);
  19571. }
  19572. };
  19573. /**
  19574. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19575. * are rendered back to front if in the same alpha index.
  19576. *
  19577. * @param a The first submesh
  19578. * @param b The second submesh
  19579. * @returns The result of the comparison
  19580. */
  19581. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19582. // Alpha index first
  19583. if (a._alphaIndex > b._alphaIndex) {
  19584. return 1;
  19585. }
  19586. if (a._alphaIndex < b._alphaIndex) {
  19587. return -1;
  19588. }
  19589. // Then distance to camera
  19590. return RenderingGroup.backToFrontSortCompare(a, b);
  19591. };
  19592. /**
  19593. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19594. * are rendered back to front.
  19595. *
  19596. * @param a The first submesh
  19597. * @param b The second submesh
  19598. * @returns The result of the comparison
  19599. */
  19600. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19601. // Then distance to camera
  19602. if (a._distanceToCamera < b._distanceToCamera) {
  19603. return 1;
  19604. }
  19605. if (a._distanceToCamera > b._distanceToCamera) {
  19606. return -1;
  19607. }
  19608. return 0;
  19609. };
  19610. /**
  19611. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19612. * are rendered front to back (prevent overdraw).
  19613. *
  19614. * @param a The first submesh
  19615. * @param b The second submesh
  19616. * @returns The result of the comparison
  19617. */
  19618. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19619. // Then distance to camera
  19620. if (a._distanceToCamera < b._distanceToCamera) {
  19621. return -1;
  19622. }
  19623. if (a._distanceToCamera > b._distanceToCamera) {
  19624. return 1;
  19625. }
  19626. return 0;
  19627. };
  19628. /**
  19629. * Resets the different lists of submeshes to prepare a new frame.
  19630. */
  19631. RenderingGroup.prototype.prepare = function () {
  19632. this._opaqueSubMeshes.reset();
  19633. this._transparentSubMeshes.reset();
  19634. this._alphaTestSubMeshes.reset();
  19635. this._particleSystems.reset();
  19636. this._spriteManagers.reset();
  19637. };
  19638. RenderingGroup.prototype.dispose = function () {
  19639. this._opaqueSubMeshes.dispose();
  19640. this._transparentSubMeshes.dispose();
  19641. this._alphaTestSubMeshes.dispose();
  19642. this._particleSystems.dispose();
  19643. this._spriteManagers.dispose();
  19644. };
  19645. /**
  19646. * Inserts the submesh in its correct queue depending on its material.
  19647. * @param subMesh The submesh to dispatch
  19648. */
  19649. RenderingGroup.prototype.dispatch = function (subMesh) {
  19650. var material = subMesh.getMaterial();
  19651. var mesh = subMesh.getMesh();
  19652. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  19653. this._transparentSubMeshes.push(subMesh);
  19654. }
  19655. else if (material.needAlphaTesting()) {
  19656. this._alphaTestSubMeshes.push(subMesh);
  19657. }
  19658. else {
  19659. this._opaqueSubMeshes.push(subMesh); // Opaque
  19660. }
  19661. };
  19662. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19663. this._spriteManagers.push(spriteManager);
  19664. };
  19665. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19666. this._particleSystems.push(particleSystem);
  19667. };
  19668. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19669. if (this._particleSystems.length === 0) {
  19670. return;
  19671. }
  19672. // Particles
  19673. var activeCamera = this._scene.activeCamera;
  19674. this._scene._particlesDuration.beginMonitoring();
  19675. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19676. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19677. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19678. continue;
  19679. }
  19680. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  19681. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19682. }
  19683. }
  19684. this._scene._particlesDuration.endMonitoring(false);
  19685. };
  19686. RenderingGroup.prototype._renderSprites = function () {
  19687. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19688. return;
  19689. }
  19690. // Sprites
  19691. var activeCamera = this._scene.activeCamera;
  19692. this._scene._spritesDuration.beginMonitoring();
  19693. for (var id = 0; id < this._spriteManagers.length; id++) {
  19694. var spriteManager = this._spriteManagers.data[id];
  19695. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19696. spriteManager.render();
  19697. }
  19698. }
  19699. this._scene._spritesDuration.endMonitoring(false);
  19700. };
  19701. return RenderingGroup;
  19702. }());
  19703. BABYLON.RenderingGroup = RenderingGroup;
  19704. })(BABYLON || (BABYLON = {}));
  19705. //# sourceMappingURL=babylon.renderingGroup.js.map
  19706. var BABYLON;
  19707. (function (BABYLON) {
  19708. var ClickInfo = (function () {
  19709. function ClickInfo() {
  19710. this._singleClick = false;
  19711. this._doubleClick = false;
  19712. this._hasSwiped = false;
  19713. this._ignore = false;
  19714. }
  19715. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19716. get: function () {
  19717. return this._singleClick;
  19718. },
  19719. set: function (b) {
  19720. this._singleClick = b;
  19721. },
  19722. enumerable: true,
  19723. configurable: true
  19724. });
  19725. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19726. get: function () {
  19727. return this._doubleClick;
  19728. },
  19729. set: function (b) {
  19730. this._doubleClick = b;
  19731. },
  19732. enumerable: true,
  19733. configurable: true
  19734. });
  19735. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19736. get: function () {
  19737. return this._hasSwiped;
  19738. },
  19739. set: function (b) {
  19740. this._hasSwiped = b;
  19741. },
  19742. enumerable: true,
  19743. configurable: true
  19744. });
  19745. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19746. get: function () {
  19747. return this._ignore;
  19748. },
  19749. set: function (b) {
  19750. this._ignore = b;
  19751. },
  19752. enumerable: true,
  19753. configurable: true
  19754. });
  19755. return ClickInfo;
  19756. }());
  19757. var PointerEventTypes = (function () {
  19758. function PointerEventTypes() {
  19759. }
  19760. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  19761. get: function () {
  19762. return PointerEventTypes._POINTERDOWN;
  19763. },
  19764. enumerable: true,
  19765. configurable: true
  19766. });
  19767. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  19768. get: function () {
  19769. return PointerEventTypes._POINTERUP;
  19770. },
  19771. enumerable: true,
  19772. configurable: true
  19773. });
  19774. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  19775. get: function () {
  19776. return PointerEventTypes._POINTERMOVE;
  19777. },
  19778. enumerable: true,
  19779. configurable: true
  19780. });
  19781. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  19782. get: function () {
  19783. return PointerEventTypes._POINTERWHEEL;
  19784. },
  19785. enumerable: true,
  19786. configurable: true
  19787. });
  19788. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  19789. get: function () {
  19790. return PointerEventTypes._POINTERPICK;
  19791. },
  19792. enumerable: true,
  19793. configurable: true
  19794. });
  19795. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  19796. get: function () {
  19797. return PointerEventTypes._POINTERTAP;
  19798. },
  19799. enumerable: true,
  19800. configurable: true
  19801. });
  19802. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  19803. get: function () {
  19804. return PointerEventTypes._POINTERDOUBLETAP;
  19805. },
  19806. enumerable: true,
  19807. configurable: true
  19808. });
  19809. return PointerEventTypes;
  19810. }());
  19811. PointerEventTypes._POINTERDOWN = 0x01;
  19812. PointerEventTypes._POINTERUP = 0x02;
  19813. PointerEventTypes._POINTERMOVE = 0x04;
  19814. PointerEventTypes._POINTERWHEEL = 0x08;
  19815. PointerEventTypes._POINTERPICK = 0x10;
  19816. PointerEventTypes._POINTERTAP = 0x20;
  19817. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  19818. BABYLON.PointerEventTypes = PointerEventTypes;
  19819. var PointerInfoBase = (function () {
  19820. function PointerInfoBase(type, event) {
  19821. this.type = type;
  19822. this.event = event;
  19823. }
  19824. return PointerInfoBase;
  19825. }());
  19826. BABYLON.PointerInfoBase = PointerInfoBase;
  19827. /**
  19828. * This class is used to store pointer related info for the onPrePointerObservable event.
  19829. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  19830. */
  19831. var PointerInfoPre = (function (_super) {
  19832. __extends(PointerInfoPre, _super);
  19833. function PointerInfoPre(type, event, localX, localY) {
  19834. var _this = _super.call(this, type, event) || this;
  19835. _this.skipOnPointerObservable = false;
  19836. _this.localPosition = new BABYLON.Vector2(localX, localY);
  19837. return _this;
  19838. }
  19839. return PointerInfoPre;
  19840. }(PointerInfoBase));
  19841. BABYLON.PointerInfoPre = PointerInfoPre;
  19842. /**
  19843. * This type contains all the data related to a pointer event in Babylon.js.
  19844. * 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.
  19845. */
  19846. var PointerInfo = (function (_super) {
  19847. __extends(PointerInfo, _super);
  19848. function PointerInfo(type, event, pickInfo) {
  19849. var _this = _super.call(this, type, event) || this;
  19850. _this.pickInfo = pickInfo;
  19851. return _this;
  19852. }
  19853. return PointerInfo;
  19854. }(PointerInfoBase));
  19855. BABYLON.PointerInfo = PointerInfo;
  19856. /**
  19857. * This class is used by the onRenderingGroupObservable
  19858. */
  19859. var RenderingGroupInfo = (function () {
  19860. function RenderingGroupInfo() {
  19861. }
  19862. return RenderingGroupInfo;
  19863. }());
  19864. /**
  19865. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19866. * This stage will be fired no matter what
  19867. */
  19868. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19869. /**
  19870. * Called before opaque object are rendered.
  19871. * This stage will be fired only if there's 3D Opaque content to render
  19872. */
  19873. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19874. /**
  19875. * Called after the opaque objects are rendered and before the transparent ones
  19876. * This stage will be fired only if there's 3D transparent content to render
  19877. */
  19878. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19879. /**
  19880. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19881. * This stage will be fired no matter what
  19882. */
  19883. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19884. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19885. /**
  19886. * Represents a scene to be rendered by the engine.
  19887. * @see http://doc.babylonjs.com/page.php?p=21911
  19888. */
  19889. var Scene = (function () {
  19890. /**
  19891. * @constructor
  19892. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19893. */
  19894. function Scene(engine) {
  19895. // Members
  19896. this.autoClear = true;
  19897. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19898. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19899. this.forceWireframe = false;
  19900. this._forcePointsCloud = false;
  19901. this.forceShowBoundingBoxes = false;
  19902. this.animationsEnabled = true;
  19903. this.constantlyUpdateMeshUnderPointer = false;
  19904. this.useRightHandedSystem = false;
  19905. this.hoverCursor = "pointer";
  19906. // Metadata
  19907. this.metadata = null;
  19908. // Events
  19909. /**
  19910. * An event triggered when the scene is disposed.
  19911. * @type {BABYLON.Observable}
  19912. */
  19913. this.onDisposeObservable = new BABYLON.Observable();
  19914. /**
  19915. * An event triggered before rendering the scene
  19916. * @type {BABYLON.Observable}
  19917. */
  19918. this.onBeforeRenderObservable = new BABYLON.Observable();
  19919. /**
  19920. * An event triggered after rendering the scene
  19921. * @type {BABYLON.Observable}
  19922. */
  19923. this.onAfterRenderObservable = new BABYLON.Observable();
  19924. /**
  19925. * An event triggered when the scene is ready
  19926. * @type {BABYLON.Observable}
  19927. */
  19928. this.onReadyObservable = new BABYLON.Observable();
  19929. /**
  19930. * An event triggered before rendering a camera
  19931. * @type {BABYLON.Observable}
  19932. */
  19933. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19934. /**
  19935. * An event triggered after rendering a camera
  19936. * @type {BABYLON.Observable}
  19937. */
  19938. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19939. /**
  19940. * An event triggered when a camera is created
  19941. * @type {BABYLON.Observable}
  19942. */
  19943. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19944. /**
  19945. * An event triggered when a camera is removed
  19946. * @type {BABYLON.Observable}
  19947. */
  19948. this.onCameraRemovedObservable = new BABYLON.Observable();
  19949. /**
  19950. * An event triggered when a light is created
  19951. * @type {BABYLON.Observable}
  19952. */
  19953. this.onNewLightAddedObservable = new BABYLON.Observable();
  19954. /**
  19955. * An event triggered when a light is removed
  19956. * @type {BABYLON.Observable}
  19957. */
  19958. this.onLightRemovedObservable = new BABYLON.Observable();
  19959. /**
  19960. * An event triggered when a geometry is created
  19961. * @type {BABYLON.Observable}
  19962. */
  19963. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19964. /**
  19965. * An event triggered when a geometry is removed
  19966. * @type {BABYLON.Observable}
  19967. */
  19968. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19969. /**
  19970. * An event triggered when a mesh is created
  19971. * @type {BABYLON.Observable}
  19972. */
  19973. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19974. /**
  19975. * An event triggered when a mesh is removed
  19976. * @type {BABYLON.Observable}
  19977. */
  19978. this.onMeshRemovedObservable = new BABYLON.Observable();
  19979. /**
  19980. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19981. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19982. * 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)
  19983. */
  19984. this.onRenderingGroupObservable = new BABYLON.Observable();
  19985. // Animations
  19986. this.animations = [];
  19987. /**
  19988. * 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).
  19989. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  19990. */
  19991. this.onPrePointerObservable = new BABYLON.Observable();
  19992. /**
  19993. * Observable event triggered each time an input event is received from the rendering canvas
  19994. */
  19995. this.onPointerObservable = new BABYLON.Observable();
  19996. this._meshPickProceed = false;
  19997. this._previousHasSwiped = false;
  19998. this._currentPickResult = null;
  19999. this._previousPickResult = null;
  20000. this._isButtonPressed = false;
  20001. this._doubleClickOccured = false;
  20002. 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
  20003. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20004. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20005. this._startingPointerTime = 0;
  20006. this._previousStartingPointerTime = 0;
  20007. // Fog
  20008. /**
  20009. * is fog enabled on this scene.
  20010. * @type {boolean}
  20011. */
  20012. this._fogEnabled = true;
  20013. this._fogMode = Scene.FOGMODE_NONE;
  20014. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20015. this.fogDensity = 0.1;
  20016. this.fogStart = 0;
  20017. this.fogEnd = 1000.0;
  20018. // Lights
  20019. /**
  20020. * is shadow enabled on this scene.
  20021. * @type {boolean}
  20022. */
  20023. this._shadowsEnabled = true;
  20024. /**
  20025. * is light enabled on this scene.
  20026. * @type {boolean}
  20027. */
  20028. this._lightsEnabled = true;
  20029. /**
  20030. * All of the lights added to this scene.
  20031. * @see BABYLON.Light
  20032. * @type {BABYLON.Light[]}
  20033. */
  20034. this.lights = new Array();
  20035. // Cameras
  20036. /**
  20037. * All of the cameras added to this scene.
  20038. * @see BABYLON.Camera
  20039. * @type {BABYLON.Camera[]}
  20040. */
  20041. this.cameras = new Array();
  20042. this.activeCameras = new Array();
  20043. // Meshes
  20044. /**
  20045. * All of the (abstract) meshes added to this scene.
  20046. * @see BABYLON.AbstractMesh
  20047. * @type {BABYLON.AbstractMesh[]}
  20048. */
  20049. this.meshes = new Array();
  20050. // Geometries
  20051. this._geometries = new Array();
  20052. this.materials = new Array();
  20053. this.multiMaterials = new Array();
  20054. // Textures
  20055. this._texturesEnabled = true;
  20056. this.textures = new Array();
  20057. // Particles
  20058. this.particlesEnabled = true;
  20059. this.particleSystems = new Array();
  20060. // Sprites
  20061. this.spritesEnabled = true;
  20062. this.spriteManagers = new Array();
  20063. // Layers
  20064. this.layers = new Array();
  20065. this.highlightLayers = new Array();
  20066. // Skeletons
  20067. this._skeletonsEnabled = true;
  20068. this.skeletons = new Array();
  20069. // Lens flares
  20070. this.lensFlaresEnabled = true;
  20071. this.lensFlareSystems = new Array();
  20072. // Collisions
  20073. this.collisionsEnabled = true;
  20074. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  20075. // Postprocesses
  20076. this.postProcessesEnabled = true;
  20077. // Customs render targets
  20078. this.renderTargetsEnabled = true;
  20079. this.dumpNextRenderTargets = false;
  20080. this.customRenderTargets = new Array();
  20081. // Imported meshes
  20082. this.importedMeshesFiles = new Array();
  20083. // Probes
  20084. this.probesEnabled = true;
  20085. this.reflectionProbes = new Array();
  20086. this._actionManagers = new Array();
  20087. this._meshesForIntersections = new BABYLON.SmartArray(256);
  20088. // Procedural textures
  20089. this.proceduralTexturesEnabled = true;
  20090. this._proceduralTextures = new Array();
  20091. this.soundTracks = new Array();
  20092. this._audioEnabled = true;
  20093. this._headphone = false;
  20094. // Performance counters
  20095. this._totalMeshesCounter = new BABYLON.PerfCounter();
  20096. this._totalLightsCounter = new BABYLON.PerfCounter();
  20097. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  20098. this._totalTexturesCounter = new BABYLON.PerfCounter();
  20099. this._totalVertices = new BABYLON.PerfCounter();
  20100. this._activeIndices = new BABYLON.PerfCounter();
  20101. this._activeParticles = new BABYLON.PerfCounter();
  20102. this._lastFrameDuration = new BABYLON.PerfCounter();
  20103. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  20104. this._renderTargetsDuration = new BABYLON.PerfCounter();
  20105. this._particlesDuration = new BABYLON.PerfCounter();
  20106. this._renderDuration = new BABYLON.PerfCounter();
  20107. this._spritesDuration = new BABYLON.PerfCounter();
  20108. this._activeBones = new BABYLON.PerfCounter();
  20109. this._animationTime = 0;
  20110. this.animationTimeScale = 1;
  20111. this._renderId = 0;
  20112. this._executeWhenReadyTimeoutId = -1;
  20113. this._intermediateRendering = false;
  20114. this._toBeDisposed = new BABYLON.SmartArray(256);
  20115. this._pendingData = []; //ANY
  20116. this._activeMeshes = new BABYLON.SmartArray(256);
  20117. this._processedMaterials = new BABYLON.SmartArray(256);
  20118. this._renderTargets = new BABYLON.SmartArray(256);
  20119. this._activeParticleSystems = new BABYLON.SmartArray(256);
  20120. this._activeSkeletons = new BABYLON.SmartArray(32);
  20121. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  20122. this._activeAnimatables = new Array();
  20123. this._transformMatrix = BABYLON.Matrix.Zero();
  20124. this._edgesRenderers = new BABYLON.SmartArray(16);
  20125. this._uniqueIdCounter = 0;
  20126. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  20127. this._engine.scenes.push(this);
  20128. this._externalData = new BABYLON.StringDictionary();
  20129. this._uid = null;
  20130. this._renderingManager = new BABYLON.RenderingManager(this);
  20131. this.postProcessManager = new BABYLON.PostProcessManager(this);
  20132. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  20133. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  20134. if (BABYLON.OutlineRenderer) {
  20135. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  20136. }
  20137. this.attachControl();
  20138. if (BABYLON.SoundTrack) {
  20139. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  20140. }
  20141. //simplification queue
  20142. if (BABYLON.SimplificationQueue) {
  20143. this.simplificationQueue = new BABYLON.SimplificationQueue();
  20144. }
  20145. //collision coordinator initialization. For now legacy per default.
  20146. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  20147. }
  20148. Object.defineProperty(Scene, "FOGMODE_NONE", {
  20149. get: function () {
  20150. return Scene._FOGMODE_NONE;
  20151. },
  20152. enumerable: true,
  20153. configurable: true
  20154. });
  20155. Object.defineProperty(Scene, "FOGMODE_EXP", {
  20156. get: function () {
  20157. return Scene._FOGMODE_EXP;
  20158. },
  20159. enumerable: true,
  20160. configurable: true
  20161. });
  20162. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  20163. get: function () {
  20164. return Scene._FOGMODE_EXP2;
  20165. },
  20166. enumerable: true,
  20167. configurable: true
  20168. });
  20169. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  20170. get: function () {
  20171. return Scene._FOGMODE_LINEAR;
  20172. },
  20173. enumerable: true,
  20174. configurable: true
  20175. });
  20176. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  20177. get: function () {
  20178. return this._forcePointsCloud;
  20179. },
  20180. set: function (value) {
  20181. if (this._forcePointsCloud === value) {
  20182. return;
  20183. }
  20184. this._forcePointsCloud = value;
  20185. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20186. },
  20187. enumerable: true,
  20188. configurable: true
  20189. });
  20190. Object.defineProperty(Scene.prototype, "onDispose", {
  20191. set: function (callback) {
  20192. if (this._onDisposeObserver) {
  20193. this.onDisposeObservable.remove(this._onDisposeObserver);
  20194. }
  20195. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20196. },
  20197. enumerable: true,
  20198. configurable: true
  20199. });
  20200. Object.defineProperty(Scene.prototype, "beforeRender", {
  20201. set: function (callback) {
  20202. if (this._onBeforeRenderObserver) {
  20203. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  20204. }
  20205. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  20206. },
  20207. enumerable: true,
  20208. configurable: true
  20209. });
  20210. Object.defineProperty(Scene.prototype, "afterRender", {
  20211. set: function (callback) {
  20212. if (this._onAfterRenderObserver) {
  20213. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  20214. }
  20215. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  20216. },
  20217. enumerable: true,
  20218. configurable: true
  20219. });
  20220. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  20221. set: function (callback) {
  20222. if (this._onBeforeCameraRenderObserver) {
  20223. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  20224. }
  20225. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  20226. },
  20227. enumerable: true,
  20228. configurable: true
  20229. });
  20230. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  20231. set: function (callback) {
  20232. if (this._onAfterCameraRenderObserver) {
  20233. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  20234. }
  20235. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  20236. },
  20237. enumerable: true,
  20238. configurable: true
  20239. });
  20240. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  20241. get: function () {
  20242. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  20243. },
  20244. enumerable: true,
  20245. configurable: true
  20246. });
  20247. Object.defineProperty(Scene.prototype, "fogEnabled", {
  20248. get: function () {
  20249. return this._fogEnabled;
  20250. },
  20251. set: function (value) {
  20252. if (this._fogEnabled === value) {
  20253. return;
  20254. }
  20255. this._fogEnabled = value;
  20256. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20257. },
  20258. enumerable: true,
  20259. configurable: true
  20260. });
  20261. Object.defineProperty(Scene.prototype, "fogMode", {
  20262. get: function () {
  20263. return this._fogMode;
  20264. },
  20265. set: function (value) {
  20266. if (this._fogMode === value) {
  20267. return;
  20268. }
  20269. this._fogMode = value;
  20270. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20271. },
  20272. enumerable: true,
  20273. configurable: true
  20274. });
  20275. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  20276. get: function () {
  20277. return this._shadowsEnabled;
  20278. },
  20279. set: function (value) {
  20280. if (this._shadowsEnabled === value) {
  20281. return;
  20282. }
  20283. this._shadowsEnabled = value;
  20284. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20285. },
  20286. enumerable: true,
  20287. configurable: true
  20288. });
  20289. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  20290. get: function () {
  20291. return this._lightsEnabled;
  20292. },
  20293. set: function (value) {
  20294. if (this._lightsEnabled === value) {
  20295. return;
  20296. }
  20297. this._lightsEnabled = value;
  20298. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20299. },
  20300. enumerable: true,
  20301. configurable: true
  20302. });
  20303. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  20304. get: function () {
  20305. if (!this._defaultMaterial) {
  20306. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  20307. }
  20308. return this._defaultMaterial;
  20309. },
  20310. enumerable: true,
  20311. configurable: true
  20312. });
  20313. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  20314. get: function () {
  20315. return this._texturesEnabled;
  20316. },
  20317. set: function (value) {
  20318. if (this._texturesEnabled === value) {
  20319. return;
  20320. }
  20321. this._texturesEnabled = value;
  20322. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20323. },
  20324. enumerable: true,
  20325. configurable: true
  20326. });
  20327. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  20328. get: function () {
  20329. return this._skeletonsEnabled;
  20330. },
  20331. set: function (value) {
  20332. if (this._skeletonsEnabled === value) {
  20333. return;
  20334. }
  20335. this._skeletonsEnabled = value;
  20336. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  20337. },
  20338. enumerable: true,
  20339. configurable: true
  20340. });
  20341. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  20342. get: function () {
  20343. return this._frustumPlanes;
  20344. },
  20345. enumerable: true,
  20346. configurable: true
  20347. });
  20348. Object.defineProperty(Scene.prototype, "debugLayer", {
  20349. // Properties
  20350. get: function () {
  20351. if (!this._debugLayer) {
  20352. this._debugLayer = new BABYLON.DebugLayer(this);
  20353. }
  20354. return this._debugLayer;
  20355. },
  20356. enumerable: true,
  20357. configurable: true
  20358. });
  20359. Object.defineProperty(Scene.prototype, "workerCollisions", {
  20360. get: function () {
  20361. return this._workerCollisions;
  20362. },
  20363. set: function (enabled) {
  20364. enabled = (enabled && !!Worker);
  20365. this._workerCollisions = enabled;
  20366. if (this.collisionCoordinator) {
  20367. this.collisionCoordinator.destroy();
  20368. }
  20369. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  20370. this.collisionCoordinator.init(this);
  20371. },
  20372. enumerable: true,
  20373. configurable: true
  20374. });
  20375. Object.defineProperty(Scene.prototype, "selectionOctree", {
  20376. get: function () {
  20377. return this._selectionOctree;
  20378. },
  20379. enumerable: true,
  20380. configurable: true
  20381. });
  20382. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  20383. /**
  20384. * The mesh that is currently under the pointer.
  20385. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  20386. */
  20387. get: function () {
  20388. return this._pointerOverMesh;
  20389. },
  20390. enumerable: true,
  20391. configurable: true
  20392. });
  20393. Object.defineProperty(Scene.prototype, "pointerX", {
  20394. /**
  20395. * Current on-screen X position of the pointer
  20396. * @return {number} X position of the pointer
  20397. */
  20398. get: function () {
  20399. return this._pointerX;
  20400. },
  20401. enumerable: true,
  20402. configurable: true
  20403. });
  20404. Object.defineProperty(Scene.prototype, "pointerY", {
  20405. /**
  20406. * Current on-screen Y position of the pointer
  20407. * @return {number} Y position of the pointer
  20408. */
  20409. get: function () {
  20410. return this._pointerY;
  20411. },
  20412. enumerable: true,
  20413. configurable: true
  20414. });
  20415. Scene.prototype.getCachedMaterial = function () {
  20416. return this._cachedMaterial;
  20417. };
  20418. Scene.prototype.getCachedEffect = function () {
  20419. return this._cachedEffect;
  20420. };
  20421. Scene.prototype.getBoundingBoxRenderer = function () {
  20422. return this._boundingBoxRenderer;
  20423. };
  20424. Scene.prototype.getOutlineRenderer = function () {
  20425. return this._outlineRenderer;
  20426. };
  20427. Scene.prototype.getEngine = function () {
  20428. return this._engine;
  20429. };
  20430. Scene.prototype.getTotalVertices = function () {
  20431. return this._totalVertices.current;
  20432. };
  20433. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20434. get: function () {
  20435. return this._totalVertices;
  20436. },
  20437. enumerable: true,
  20438. configurable: true
  20439. });
  20440. Scene.prototype.getActiveIndices = function () {
  20441. return this._activeIndices.current;
  20442. };
  20443. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20444. get: function () {
  20445. return this._activeIndices;
  20446. },
  20447. enumerable: true,
  20448. configurable: true
  20449. });
  20450. Scene.prototype.getActiveParticles = function () {
  20451. return this._activeParticles.current;
  20452. };
  20453. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20454. get: function () {
  20455. return this._activeParticles;
  20456. },
  20457. enumerable: true,
  20458. configurable: true
  20459. });
  20460. Scene.prototype.getActiveBones = function () {
  20461. return this._activeBones.current;
  20462. };
  20463. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20464. get: function () {
  20465. return this._activeBones;
  20466. },
  20467. enumerable: true,
  20468. configurable: true
  20469. });
  20470. // Stats
  20471. Scene.prototype.getLastFrameDuration = function () {
  20472. return this._lastFrameDuration.current;
  20473. };
  20474. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20475. get: function () {
  20476. return this._lastFrameDuration;
  20477. },
  20478. enumerable: true,
  20479. configurable: true
  20480. });
  20481. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20482. return this._evaluateActiveMeshesDuration.current;
  20483. };
  20484. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20485. get: function () {
  20486. return this._evaluateActiveMeshesDuration;
  20487. },
  20488. enumerable: true,
  20489. configurable: true
  20490. });
  20491. Scene.prototype.getActiveMeshes = function () {
  20492. return this._activeMeshes;
  20493. };
  20494. Scene.prototype.getRenderTargetsDuration = function () {
  20495. return this._renderTargetsDuration.current;
  20496. };
  20497. Scene.prototype.getRenderDuration = function () {
  20498. return this._renderDuration.current;
  20499. };
  20500. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20501. get: function () {
  20502. return this._renderDuration;
  20503. },
  20504. enumerable: true,
  20505. configurable: true
  20506. });
  20507. Scene.prototype.getParticlesDuration = function () {
  20508. return this._particlesDuration.current;
  20509. };
  20510. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20511. get: function () {
  20512. return this._particlesDuration;
  20513. },
  20514. enumerable: true,
  20515. configurable: true
  20516. });
  20517. Scene.prototype.getSpritesDuration = function () {
  20518. return this._spritesDuration.current;
  20519. };
  20520. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20521. get: function () {
  20522. return this._spritesDuration;
  20523. },
  20524. enumerable: true,
  20525. configurable: true
  20526. });
  20527. Scene.prototype.getAnimationRatio = function () {
  20528. return this._animationRatio;
  20529. };
  20530. Scene.prototype.getRenderId = function () {
  20531. return this._renderId;
  20532. };
  20533. Scene.prototype.incrementRenderId = function () {
  20534. this._renderId++;
  20535. };
  20536. Scene.prototype._updatePointerPosition = function (evt) {
  20537. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20538. this._pointerX = evt.clientX - canvasRect.left;
  20539. this._pointerY = evt.clientY - canvasRect.top;
  20540. this._unTranslatedPointerX = this._pointerX;
  20541. this._unTranslatedPointerY = this._pointerY;
  20542. if (this.cameraToUseForPointers) {
  20543. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  20544. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  20545. }
  20546. };
  20547. // Pointers handling
  20548. /**
  20549. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20550. * @param attachUp defines if you want to attach events to pointerup
  20551. * @param attachDown defines if you want to attach events to pointerdown
  20552. * @param attachMove defines if you want to attach events to pointermove
  20553. */
  20554. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20555. var _this = this;
  20556. if (attachUp === void 0) { attachUp = true; }
  20557. if (attachDown === void 0) { attachDown = true; }
  20558. if (attachMove === void 0) { attachMove = true; }
  20559. this._initActionManager = function (act, clickInfo) {
  20560. if (!_this._meshPickProceed) {
  20561. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20562. _this._currentPickResult = pickResult;
  20563. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20564. _this._meshPickProceed = true;
  20565. }
  20566. return act;
  20567. };
  20568. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20569. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20570. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20571. btn !== _this._previousButtonPressed) {
  20572. _this._doubleClickOccured = false;
  20573. clickInfo.singleClick = true;
  20574. clickInfo.ignore = false;
  20575. cb(clickInfo, _this._currentPickResult);
  20576. }
  20577. };
  20578. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20579. var clickInfo = new ClickInfo();
  20580. _this._currentPickResult = null;
  20581. var act;
  20582. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  20583. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  20584. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20585. if (!checkPicking && BABYLON.ActionManager.HasPickTriggers) {
  20586. act = _this._initActionManager(act, clickInfo);
  20587. if (act)
  20588. checkPicking = act.hasPickTriggers;
  20589. }
  20590. if (checkPicking) {
  20591. var btn = evt.button;
  20592. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20593. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20594. if (!clickInfo.hasSwiped) {
  20595. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20596. if (!checkSingleClickImmediately) {
  20597. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  20598. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20599. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20600. act = _this._initActionManager(act, clickInfo);
  20601. if (act)
  20602. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20603. }
  20604. }
  20605. if (checkSingleClickImmediately) {
  20606. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20607. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20608. btn !== _this._previousButtonPressed) {
  20609. clickInfo.singleClick = true;
  20610. cb(clickInfo, _this._currentPickResult);
  20611. }
  20612. }
  20613. else {
  20614. // wait that no double click has been raised during the double click delay
  20615. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20616. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20617. }
  20618. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  20619. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20620. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20621. act = _this._initActionManager(act, clickInfo);
  20622. if (act)
  20623. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20624. }
  20625. if (checkDoubleClick) {
  20626. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20627. if (btn === _this._previousButtonPressed &&
  20628. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20629. !_this._doubleClickOccured) {
  20630. // pointer has not moved for 2 clicks, it's a double click
  20631. if (!clickInfo.hasSwiped &&
  20632. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20633. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20634. _this._previousStartingPointerTime = 0;
  20635. _this._doubleClickOccured = true;
  20636. clickInfo.doubleClick = true;
  20637. clickInfo.ignore = false;
  20638. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  20639. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  20640. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20641. cb(clickInfo, _this._currentPickResult);
  20642. }
  20643. else {
  20644. _this._doubleClickOccured = false;
  20645. _this._previousStartingPointerTime = _this._startingPointerTime;
  20646. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20647. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20648. _this._previousButtonPressed = btn;
  20649. _this._previousHasSwiped = clickInfo.hasSwiped;
  20650. if (Scene.ExclusiveDoubleClickMode) {
  20651. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  20652. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  20653. }
  20654. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20655. cb(clickInfo, _this._previousPickResult);
  20656. }
  20657. else {
  20658. cb(clickInfo, _this._currentPickResult);
  20659. }
  20660. }
  20661. }
  20662. else {
  20663. _this._doubleClickOccured = false;
  20664. _this._previousStartingPointerTime = _this._startingPointerTime;
  20665. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20666. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20667. _this._previousButtonPressed = btn;
  20668. _this._previousHasSwiped = clickInfo.hasSwiped;
  20669. }
  20670. }
  20671. }
  20672. }
  20673. clickInfo.ignore = true;
  20674. cb(clickInfo, _this._currentPickResult);
  20675. };
  20676. var spritePredicate = function (sprite) {
  20677. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20678. };
  20679. this._onPointerMove = function (evt) {
  20680. _this._updatePointerPosition(evt);
  20681. // PreObservable support
  20682. if (_this.onPrePointerObservable.hasObservers()) {
  20683. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  20684. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20685. _this.onPrePointerObservable.notifyObservers(pi, type);
  20686. if (pi.skipOnPointerObservable) {
  20687. return;
  20688. }
  20689. }
  20690. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20691. return;
  20692. }
  20693. var canvas = _this._engine.getRenderingCanvas();
  20694. if (!_this.pointerMovePredicate) {
  20695. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20696. }
  20697. // Meshes
  20698. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20699. if (pickResult.hit && pickResult.pickedMesh) {
  20700. _this.setPointerOverSprite(null);
  20701. _this.setPointerOverMesh(pickResult.pickedMesh);
  20702. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20703. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  20704. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  20705. }
  20706. else {
  20707. canvas.style.cursor = _this.hoverCursor;
  20708. }
  20709. }
  20710. else {
  20711. canvas.style.cursor = "";
  20712. }
  20713. }
  20714. else {
  20715. _this.setPointerOverMesh(null);
  20716. // Sprites
  20717. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  20718. if (pickResult.hit && pickResult.pickedSprite) {
  20719. _this.setPointerOverSprite(pickResult.pickedSprite);
  20720. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  20721. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  20722. }
  20723. else {
  20724. canvas.style.cursor = _this.hoverCursor;
  20725. }
  20726. }
  20727. else {
  20728. _this.setPointerOverSprite(null);
  20729. // Restore pointer
  20730. canvas.style.cursor = "";
  20731. }
  20732. }
  20733. if (_this.onPointerMove) {
  20734. _this.onPointerMove(evt, pickResult);
  20735. }
  20736. if (_this.onPointerObservable.hasObservers()) {
  20737. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  20738. var pi = new PointerInfo(type, evt, pickResult);
  20739. _this.onPointerObservable.notifyObservers(pi, type);
  20740. }
  20741. };
  20742. this._onPointerDown = function (evt) {
  20743. _this._isButtonPressed = true;
  20744. _this._pickedDownMesh = null;
  20745. _this._meshPickProceed = false;
  20746. _this._updatePointerPosition(evt);
  20747. // PreObservable support
  20748. if (_this.onPrePointerObservable.hasObservers()) {
  20749. var type = PointerEventTypes.POINTERDOWN;
  20750. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20751. _this.onPrePointerObservable.notifyObservers(pi, type);
  20752. if (pi.skipOnPointerObservable) {
  20753. return;
  20754. }
  20755. }
  20756. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20757. return;
  20758. }
  20759. _this._startingPointerPosition.x = _this._pointerX;
  20760. _this._startingPointerPosition.y = _this._pointerY;
  20761. _this._startingPointerTime = new Date().getTime();
  20762. if (!_this.pointerDownPredicate) {
  20763. _this.pointerDownPredicate = function (mesh) {
  20764. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  20765. };
  20766. }
  20767. // Meshes
  20768. _this._pickedDownMesh = null;
  20769. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20770. if (pickResult.hit && pickResult.pickedMesh) {
  20771. _this._pickedDownMesh = pickResult.pickedMesh;
  20772. var actionManager = pickResult.pickedMesh.actionManager;
  20773. if (actionManager) {
  20774. if (actionManager.hasPickTriggers) {
  20775. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20776. switch (evt.button) {
  20777. case 0:
  20778. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20779. break;
  20780. case 1:
  20781. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20782. break;
  20783. case 2:
  20784. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20785. break;
  20786. }
  20787. }
  20788. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20789. window.setTimeout((function () {
  20790. var _this = this;
  20791. 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);
  20792. if (pickResult.hit && pickResult.pickedMesh) {
  20793. if (this._isButtonPressed &&
  20794. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  20795. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  20796. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  20797. this._startingPointerTime = 0;
  20798. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20799. }
  20800. }
  20801. }).bind(_this), Scene.LongPressDelay);
  20802. }
  20803. }
  20804. }
  20805. if (_this.onPointerDown) {
  20806. _this.onPointerDown(evt, pickResult);
  20807. }
  20808. if (_this.onPointerObservable.hasObservers()) {
  20809. var type = PointerEventTypes.POINTERDOWN;
  20810. var pi = new PointerInfo(type, evt, pickResult);
  20811. _this.onPointerObservable.notifyObservers(pi, type);
  20812. }
  20813. // Sprites
  20814. _this._pickedDownSprite = null;
  20815. if (_this.spriteManagers.length > 0) {
  20816. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  20817. if (pickResult.hit && pickResult.pickedSprite) {
  20818. if (pickResult.pickedSprite.actionManager) {
  20819. _this._pickedDownSprite = pickResult.pickedSprite;
  20820. switch (evt.button) {
  20821. case 0:
  20822. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20823. break;
  20824. case 1:
  20825. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20826. break;
  20827. case 2:
  20828. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20829. break;
  20830. }
  20831. if (pickResult.pickedSprite.actionManager) {
  20832. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20833. }
  20834. }
  20835. }
  20836. }
  20837. };
  20838. this._onPointerUp = function (evt) {
  20839. _this._isButtonPressed = false;
  20840. _this._pickedUpMesh = null;
  20841. _this._meshPickProceed = false;
  20842. _this._updatePointerPosition(evt);
  20843. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  20844. // PreObservable support
  20845. if (this.onPrePointerObservable.hasObservers()) {
  20846. if (!clickInfo.ignore) {
  20847. if (!clickInfo.hasSwiped) {
  20848. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  20849. var type = PointerEventTypes.POINTERTAP;
  20850. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20851. this.onPrePointerObservable.notifyObservers(pi, type);
  20852. if (pi.skipOnPointerObservable) {
  20853. return;
  20854. }
  20855. }
  20856. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  20857. var type = PointerEventTypes.POINTERDOUBLETAP;
  20858. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20859. this.onPrePointerObservable.notifyObservers(pi, type);
  20860. if (pi.skipOnPointerObservable) {
  20861. return;
  20862. }
  20863. }
  20864. }
  20865. }
  20866. else {
  20867. var type = PointerEventTypes.POINTERUP;
  20868. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20869. this.onPrePointerObservable.notifyObservers(pi, type);
  20870. if (pi.skipOnPointerObservable) {
  20871. return;
  20872. }
  20873. }
  20874. }
  20875. if (!this.cameraToUseForPointers && !this.activeCamera) {
  20876. return;
  20877. }
  20878. if (!this.pointerUpPredicate) {
  20879. this.pointerUpPredicate = function (mesh) {
  20880. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  20881. };
  20882. }
  20883. // Meshes
  20884. if (!this._meshPickProceed && (BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  20885. this._initActionManager(null, clickInfo);
  20886. }
  20887. if (!pickResult) {
  20888. pickResult = this._currentPickResult;
  20889. }
  20890. if (pickResult && pickResult.pickedMesh) {
  20891. this._pickedUpMesh = pickResult.pickedMesh;
  20892. if (this._pickedDownMesh === this._pickedUpMesh) {
  20893. if (this.onPointerPick) {
  20894. this.onPointerPick(evt, pickResult);
  20895. }
  20896. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20897. var type = PointerEventTypes.POINTERPICK;
  20898. var pi = new PointerInfo(type, evt, pickResult);
  20899. this.onPointerObservable.notifyObservers(pi, type);
  20900. }
  20901. }
  20902. if (pickResult.pickedMesh.actionManager) {
  20903. if (clickInfo.ignore) {
  20904. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20905. }
  20906. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20907. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20908. }
  20909. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20910. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20911. }
  20912. }
  20913. }
  20914. if (this._pickedDownMesh &&
  20915. this._pickedDownMesh.actionManager &&
  20916. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20917. this._pickedDownMesh !== this._pickedUpMesh) {
  20918. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20919. }
  20920. if (this.onPointerUp) {
  20921. this.onPointerUp(evt, pickResult);
  20922. }
  20923. if (this.onPointerObservable.hasObservers()) {
  20924. if (!clickInfo.ignore) {
  20925. if (!clickInfo.hasSwiped) {
  20926. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  20927. var type = PointerEventTypes.POINTERTAP;
  20928. var pi = new PointerInfo(type, evt, pickResult);
  20929. this.onPointerObservable.notifyObservers(pi, type);
  20930. }
  20931. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  20932. var type = PointerEventTypes.POINTERDOUBLETAP;
  20933. var pi = new PointerInfo(type, evt, pickResult);
  20934. this.onPointerObservable.notifyObservers(pi, type);
  20935. }
  20936. }
  20937. }
  20938. else {
  20939. var type = PointerEventTypes.POINTERUP;
  20940. var pi = new PointerInfo(type, evt, pickResult);
  20941. this.onPointerObservable.notifyObservers(pi, type);
  20942. }
  20943. }
  20944. // Sprites
  20945. if (this.spriteManagers.length > 0) {
  20946. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  20947. if (pickResult.hit && pickResult.pickedSprite) {
  20948. if (pickResult.pickedSprite.actionManager) {
  20949. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  20950. if (pickResult.pickedSprite.actionManager) {
  20951. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  20952. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  20953. }
  20954. }
  20955. }
  20956. }
  20957. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  20958. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  20959. }
  20960. }
  20961. this._previousPickResult = this._currentPickResult;
  20962. }).bind(_this));
  20963. };
  20964. this._onKeyDown = function (evt) {
  20965. if (_this.actionManager) {
  20966. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20967. }
  20968. };
  20969. this._onKeyUp = function (evt) {
  20970. if (_this.actionManager) {
  20971. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20972. }
  20973. };
  20974. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20975. var canvas = this._engine.getRenderingCanvas();
  20976. if (attachMove) {
  20977. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20978. // Wheel
  20979. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20980. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20981. }
  20982. if (attachDown) {
  20983. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20984. }
  20985. if (attachUp) {
  20986. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20987. }
  20988. canvas.tabIndex = 1;
  20989. canvas.addEventListener("keydown", this._onKeyDown, false);
  20990. canvas.addEventListener("keyup", this._onKeyUp, false);
  20991. };
  20992. Scene.prototype.detachControl = function () {
  20993. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20994. var canvas = this._engine.getRenderingCanvas();
  20995. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20996. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20997. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20998. // Wheel
  20999. canvas.removeEventListener('mousewheel', this._onPointerMove);
  21000. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  21001. canvas.removeEventListener("keydown", this._onKeyDown);
  21002. canvas.removeEventListener("keyup", this._onKeyUp);
  21003. };
  21004. // Ready
  21005. Scene.prototype.isReady = function () {
  21006. if (this._pendingData.length > 0) {
  21007. return false;
  21008. }
  21009. var index;
  21010. for (index = 0; index < this._geometries.length; index++) {
  21011. var geometry = this._geometries[index];
  21012. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21013. return false;
  21014. }
  21015. }
  21016. for (index = 0; index < this.meshes.length; index++) {
  21017. var mesh = this.meshes[index];
  21018. if (!mesh.isEnabled()) {
  21019. continue;
  21020. }
  21021. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  21022. continue;
  21023. }
  21024. if (!mesh.isReady()) {
  21025. return false;
  21026. }
  21027. var mat = mesh.material;
  21028. if (mat) {
  21029. if (!mat.isReady(mesh)) {
  21030. return false;
  21031. }
  21032. }
  21033. }
  21034. return true;
  21035. };
  21036. Scene.prototype.resetCachedMaterial = function () {
  21037. this._cachedMaterial = null;
  21038. this._cachedEffect = null;
  21039. };
  21040. Scene.prototype.registerBeforeRender = function (func) {
  21041. this.onBeforeRenderObservable.add(func);
  21042. };
  21043. Scene.prototype.unregisterBeforeRender = function (func) {
  21044. this.onBeforeRenderObservable.removeCallback(func);
  21045. };
  21046. Scene.prototype.registerAfterRender = function (func) {
  21047. this.onAfterRenderObservable.add(func);
  21048. };
  21049. Scene.prototype.unregisterAfterRender = function (func) {
  21050. this.onAfterRenderObservable.removeCallback(func);
  21051. };
  21052. Scene.prototype._addPendingData = function (data) {
  21053. this._pendingData.push(data);
  21054. };
  21055. Scene.prototype._removePendingData = function (data) {
  21056. var index = this._pendingData.indexOf(data);
  21057. if (index !== -1) {
  21058. this._pendingData.splice(index, 1);
  21059. }
  21060. };
  21061. Scene.prototype.getWaitingItemsCount = function () {
  21062. return this._pendingData.length;
  21063. };
  21064. /**
  21065. * Registers a function to be executed when the scene is ready.
  21066. * @param {Function} func - the function to be executed.
  21067. */
  21068. Scene.prototype.executeWhenReady = function (func) {
  21069. var _this = this;
  21070. this.onReadyObservable.add(func);
  21071. if (this._executeWhenReadyTimeoutId !== -1) {
  21072. return;
  21073. }
  21074. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21075. _this._checkIsReady();
  21076. }, 150);
  21077. };
  21078. Scene.prototype._checkIsReady = function () {
  21079. var _this = this;
  21080. if (this.isReady()) {
  21081. this.onReadyObservable.notifyObservers(this);
  21082. this.onReadyObservable.clear();
  21083. this._executeWhenReadyTimeoutId = -1;
  21084. return;
  21085. }
  21086. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21087. _this._checkIsReady();
  21088. }, 150);
  21089. };
  21090. // Animations
  21091. /**
  21092. * Will start the animation sequence of a given target
  21093. * @param target - the target
  21094. * @param {number} from - from which frame should animation start
  21095. * @param {number} to - till which frame should animation run.
  21096. * @param {boolean} [loop] - should the animation loop
  21097. * @param {number} [speedRatio] - the speed in which to run the animation
  21098. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  21099. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  21100. * @return {BABYLON.Animatable} the animatable object created for this animation
  21101. * @see BABYLON.Animatable
  21102. * @see http://doc.babylonjs.com/page.php?p=22081
  21103. */
  21104. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  21105. if (speedRatio === void 0) { speedRatio = 1.0; }
  21106. this.stopAnimation(target);
  21107. if (!animatable) {
  21108. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  21109. }
  21110. // Local animations
  21111. if (target.animations) {
  21112. animatable.appendAnimations(target, target.animations);
  21113. }
  21114. // Children animations
  21115. if (target.getAnimatables) {
  21116. var animatables = target.getAnimatables();
  21117. for (var index = 0; index < animatables.length; index++) {
  21118. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  21119. }
  21120. }
  21121. animatable.reset();
  21122. return animatable;
  21123. };
  21124. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21125. if (speedRatio === undefined) {
  21126. speedRatio = 1.0;
  21127. }
  21128. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  21129. return animatable;
  21130. };
  21131. Scene.prototype.getAnimatableByTarget = function (target) {
  21132. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21133. if (this._activeAnimatables[index].target === target) {
  21134. return this._activeAnimatables[index];
  21135. }
  21136. }
  21137. return null;
  21138. };
  21139. Object.defineProperty(Scene.prototype, "Animatables", {
  21140. get: function () {
  21141. return this._activeAnimatables;
  21142. },
  21143. enumerable: true,
  21144. configurable: true
  21145. });
  21146. /**
  21147. * Will stop the animation of the given target
  21148. * @param target - the target
  21149. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  21150. * @see beginAnimation
  21151. */
  21152. Scene.prototype.stopAnimation = function (target, animationName) {
  21153. var animatable = this.getAnimatableByTarget(target);
  21154. if (animatable) {
  21155. animatable.stop(animationName);
  21156. }
  21157. };
  21158. Scene.prototype._animate = function () {
  21159. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  21160. return;
  21161. }
  21162. // Getting time
  21163. var now = BABYLON.Tools.Now;
  21164. if (!this._animationTimeLast) {
  21165. if (this._pendingData.length > 0) {
  21166. return;
  21167. }
  21168. this._animationTimeLast = now;
  21169. }
  21170. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  21171. this._animationTime += deltaTime;
  21172. this._animationTimeLast = now;
  21173. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21174. this._activeAnimatables[index]._animate(this._animationTime);
  21175. }
  21176. };
  21177. // Matrix
  21178. Scene.prototype.getViewMatrix = function () {
  21179. return this._viewMatrix;
  21180. };
  21181. Scene.prototype.getProjectionMatrix = function () {
  21182. return this._projectionMatrix;
  21183. };
  21184. Scene.prototype.getTransformMatrix = function () {
  21185. return this._transformMatrix;
  21186. };
  21187. Scene.prototype.setTransformMatrix = function (view, projection) {
  21188. this._viewMatrix = view;
  21189. this._projectionMatrix = projection;
  21190. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21191. // Update frustum
  21192. if (!this._frustumPlanes) {
  21193. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21194. }
  21195. else {
  21196. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21197. }
  21198. };
  21199. // Methods
  21200. Scene.prototype.addMesh = function (newMesh) {
  21201. newMesh.uniqueId = this._uniqueIdCounter++;
  21202. var position = this.meshes.push(newMesh);
  21203. //notify the collision coordinator
  21204. this.collisionCoordinator.onMeshAdded(newMesh);
  21205. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21206. };
  21207. Scene.prototype.removeMesh = function (toRemove) {
  21208. var index = this.meshes.indexOf(toRemove);
  21209. if (index !== -1) {
  21210. // Remove from the scene if mesh found
  21211. this.meshes.splice(index, 1);
  21212. }
  21213. //notify the collision coordinator
  21214. this.collisionCoordinator.onMeshRemoved(toRemove);
  21215. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21216. return index;
  21217. };
  21218. Scene.prototype.removeSkeleton = function (toRemove) {
  21219. var index = this.skeletons.indexOf(toRemove);
  21220. if (index !== -1) {
  21221. // Remove from the scene if mesh found
  21222. this.skeletons.splice(index, 1);
  21223. }
  21224. return index;
  21225. };
  21226. Scene.prototype.removeLight = function (toRemove) {
  21227. var index = this.lights.indexOf(toRemove);
  21228. if (index !== -1) {
  21229. // Remove from the scene if mesh found
  21230. this.lights.splice(index, 1);
  21231. }
  21232. this.onLightRemovedObservable.notifyObservers(toRemove);
  21233. return index;
  21234. };
  21235. Scene.prototype.removeCamera = function (toRemove) {
  21236. var index = this.cameras.indexOf(toRemove);
  21237. if (index !== -1) {
  21238. // Remove from the scene if mesh found
  21239. this.cameras.splice(index, 1);
  21240. }
  21241. // Remove from activeCameras
  21242. var index2 = this.activeCameras.indexOf(toRemove);
  21243. if (index2 !== -1) {
  21244. // Remove from the scene if mesh found
  21245. this.activeCameras.splice(index2, 1);
  21246. }
  21247. // Reset the activeCamera
  21248. if (this.activeCamera === toRemove) {
  21249. if (this.cameras.length > 0) {
  21250. this.activeCamera = this.cameras[0];
  21251. }
  21252. else {
  21253. this.activeCamera = null;
  21254. }
  21255. }
  21256. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21257. return index;
  21258. };
  21259. Scene.prototype.addLight = function (newLight) {
  21260. newLight.uniqueId = this._uniqueIdCounter++;
  21261. var position = this.lights.push(newLight);
  21262. this.onNewLightAddedObservable.notifyObservers(newLight);
  21263. };
  21264. Scene.prototype.addCamera = function (newCamera) {
  21265. newCamera.uniqueId = this._uniqueIdCounter++;
  21266. var position = this.cameras.push(newCamera);
  21267. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21268. };
  21269. /**
  21270. * Switch active camera
  21271. * @param {Camera} newCamera - new active camera
  21272. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21273. */
  21274. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21275. if (attachControl === void 0) { attachControl = true; }
  21276. var canvas = this._engine.getRenderingCanvas();
  21277. this.activeCamera.detachControl(canvas);
  21278. this.activeCamera = newCamera;
  21279. if (attachControl) {
  21280. newCamera.attachControl(canvas);
  21281. }
  21282. };
  21283. /**
  21284. * sets the active camera of the scene using its ID
  21285. * @param {string} id - the camera's ID
  21286. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21287. * @see activeCamera
  21288. */
  21289. Scene.prototype.setActiveCameraByID = function (id) {
  21290. var camera = this.getCameraByID(id);
  21291. if (camera) {
  21292. this.activeCamera = camera;
  21293. return camera;
  21294. }
  21295. return null;
  21296. };
  21297. /**
  21298. * sets the active camera of the scene using its name
  21299. * @param {string} name - the camera's name
  21300. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21301. * @see activeCamera
  21302. */
  21303. Scene.prototype.setActiveCameraByName = function (name) {
  21304. var camera = this.getCameraByName(name);
  21305. if (camera) {
  21306. this.activeCamera = camera;
  21307. return camera;
  21308. }
  21309. return null;
  21310. };
  21311. /**
  21312. * get a material using its id
  21313. * @param {string} the material's ID
  21314. * @return {BABYLON.Material|null} the material or null if none found.
  21315. */
  21316. Scene.prototype.getMaterialByID = function (id) {
  21317. for (var index = 0; index < this.materials.length; index++) {
  21318. if (this.materials[index].id === id) {
  21319. return this.materials[index];
  21320. }
  21321. }
  21322. return null;
  21323. };
  21324. /**
  21325. * get a material using its name
  21326. * @param {string} the material's name
  21327. * @return {BABYLON.Material|null} the material or null if none found.
  21328. */
  21329. Scene.prototype.getMaterialByName = function (name) {
  21330. for (var index = 0; index < this.materials.length; index++) {
  21331. if (this.materials[index].name === name) {
  21332. return this.materials[index];
  21333. }
  21334. }
  21335. return null;
  21336. };
  21337. Scene.prototype.getLensFlareSystemByName = function (name) {
  21338. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21339. if (this.lensFlareSystems[index].name === name) {
  21340. return this.lensFlareSystems[index];
  21341. }
  21342. }
  21343. return null;
  21344. };
  21345. Scene.prototype.getLensFlareSystemByID = function (id) {
  21346. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21347. if (this.lensFlareSystems[index].id === id) {
  21348. return this.lensFlareSystems[index];
  21349. }
  21350. }
  21351. return null;
  21352. };
  21353. Scene.prototype.getCameraByID = function (id) {
  21354. for (var index = 0; index < this.cameras.length; index++) {
  21355. if (this.cameras[index].id === id) {
  21356. return this.cameras[index];
  21357. }
  21358. }
  21359. return null;
  21360. };
  21361. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21362. for (var index = 0; index < this.cameras.length; index++) {
  21363. if (this.cameras[index].uniqueId === uniqueId) {
  21364. return this.cameras[index];
  21365. }
  21366. }
  21367. return null;
  21368. };
  21369. /**
  21370. * get a camera using its name
  21371. * @param {string} the camera's name
  21372. * @return {BABYLON.Camera|null} the camera or null if none found.
  21373. */
  21374. Scene.prototype.getCameraByName = function (name) {
  21375. for (var index = 0; index < this.cameras.length; index++) {
  21376. if (this.cameras[index].name === name) {
  21377. return this.cameras[index];
  21378. }
  21379. }
  21380. return null;
  21381. };
  21382. /**
  21383. * get a bone using its id
  21384. * @param {string} the bone's id
  21385. * @return {BABYLON.Bone|null} the bone or null if not found
  21386. */
  21387. Scene.prototype.getBoneByID = function (id) {
  21388. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21389. var skeleton = this.skeletons[skeletonIndex];
  21390. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21391. if (skeleton.bones[boneIndex].id === id) {
  21392. return skeleton.bones[boneIndex];
  21393. }
  21394. }
  21395. }
  21396. return null;
  21397. };
  21398. /**
  21399. * get a bone using its id
  21400. * @param {string} the bone's name
  21401. * @return {BABYLON.Bone|null} the bone or null if not found
  21402. */
  21403. Scene.prototype.getBoneByName = function (name) {
  21404. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21405. var skeleton = this.skeletons[skeletonIndex];
  21406. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21407. if (skeleton.bones[boneIndex].name === name) {
  21408. return skeleton.bones[boneIndex];
  21409. }
  21410. }
  21411. }
  21412. return null;
  21413. };
  21414. /**
  21415. * get a light node using its name
  21416. * @param {string} the light's name
  21417. * @return {BABYLON.Light|null} the light or null if none found.
  21418. */
  21419. Scene.prototype.getLightByName = function (name) {
  21420. for (var index = 0; index < this.lights.length; index++) {
  21421. if (this.lights[index].name === name) {
  21422. return this.lights[index];
  21423. }
  21424. }
  21425. return null;
  21426. };
  21427. /**
  21428. * get a light node using its ID
  21429. * @param {string} the light's id
  21430. * @return {BABYLON.Light|null} the light or null if none found.
  21431. */
  21432. Scene.prototype.getLightByID = function (id) {
  21433. for (var index = 0; index < this.lights.length; index++) {
  21434. if (this.lights[index].id === id) {
  21435. return this.lights[index];
  21436. }
  21437. }
  21438. return null;
  21439. };
  21440. /**
  21441. * get a light node using its scene-generated unique ID
  21442. * @param {number} the light's unique id
  21443. * @return {BABYLON.Light|null} the light or null if none found.
  21444. */
  21445. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21446. for (var index = 0; index < this.lights.length; index++) {
  21447. if (this.lights[index].uniqueId === uniqueId) {
  21448. return this.lights[index];
  21449. }
  21450. }
  21451. return null;
  21452. };
  21453. /**
  21454. * get a particle system by id
  21455. * @param id {number} the particle system id
  21456. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  21457. */
  21458. Scene.prototype.getParticleSystemByID = function (id) {
  21459. for (var index = 0; index < this.particleSystems.length; index++) {
  21460. if (this.particleSystems[index].id === id) {
  21461. return this.particleSystems[index];
  21462. }
  21463. }
  21464. return null;
  21465. };
  21466. /**
  21467. * get a geometry using its ID
  21468. * @param {string} the geometry's id
  21469. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21470. */
  21471. Scene.prototype.getGeometryByID = function (id) {
  21472. for (var index = 0; index < this._geometries.length; index++) {
  21473. if (this._geometries[index].id === id) {
  21474. return this._geometries[index];
  21475. }
  21476. }
  21477. return null;
  21478. };
  21479. /**
  21480. * add a new geometry to this scene.
  21481. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21482. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21483. * @return {boolean} was the geometry added or not
  21484. */
  21485. Scene.prototype.pushGeometry = function (geometry, force) {
  21486. if (!force && this.getGeometryByID(geometry.id)) {
  21487. return false;
  21488. }
  21489. this._geometries.push(geometry);
  21490. //notify the collision coordinator
  21491. this.collisionCoordinator.onGeometryAdded(geometry);
  21492. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21493. return true;
  21494. };
  21495. /**
  21496. * Removes an existing geometry
  21497. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21498. * @return {boolean} was the geometry removed or not
  21499. */
  21500. Scene.prototype.removeGeometry = function (geometry) {
  21501. var index = this._geometries.indexOf(geometry);
  21502. if (index > -1) {
  21503. this._geometries.splice(index, 1);
  21504. //notify the collision coordinator
  21505. this.collisionCoordinator.onGeometryDeleted(geometry);
  21506. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21507. return true;
  21508. }
  21509. return false;
  21510. };
  21511. Scene.prototype.getGeometries = function () {
  21512. return this._geometries;
  21513. };
  21514. /**
  21515. * Get the first added mesh found of a given ID
  21516. * @param {string} id - the id to search for
  21517. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21518. */
  21519. Scene.prototype.getMeshByID = function (id) {
  21520. for (var index = 0; index < this.meshes.length; index++) {
  21521. if (this.meshes[index].id === id) {
  21522. return this.meshes[index];
  21523. }
  21524. }
  21525. return null;
  21526. };
  21527. Scene.prototype.getMeshesByID = function (id) {
  21528. return this.meshes.filter(function (m) {
  21529. return m.id === id;
  21530. });
  21531. };
  21532. /**
  21533. * Get a mesh with its auto-generated unique id
  21534. * @param {number} uniqueId - the unique id to search for
  21535. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21536. */
  21537. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21538. for (var index = 0; index < this.meshes.length; index++) {
  21539. if (this.meshes[index].uniqueId === uniqueId) {
  21540. return this.meshes[index];
  21541. }
  21542. }
  21543. return null;
  21544. };
  21545. /**
  21546. * Get a the last added mesh found of a given ID
  21547. * @param {string} id - the id to search for
  21548. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21549. */
  21550. Scene.prototype.getLastMeshByID = function (id) {
  21551. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21552. if (this.meshes[index].id === id) {
  21553. return this.meshes[index];
  21554. }
  21555. }
  21556. return null;
  21557. };
  21558. /**
  21559. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21560. * @param {string} id - the id to search for
  21561. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21562. */
  21563. Scene.prototype.getLastEntryByID = function (id) {
  21564. var index;
  21565. for (index = this.meshes.length - 1; index >= 0; index--) {
  21566. if (this.meshes[index].id === id) {
  21567. return this.meshes[index];
  21568. }
  21569. }
  21570. for (index = this.cameras.length - 1; index >= 0; index--) {
  21571. if (this.cameras[index].id === id) {
  21572. return this.cameras[index];
  21573. }
  21574. }
  21575. for (index = this.lights.length - 1; index >= 0; index--) {
  21576. if (this.lights[index].id === id) {
  21577. return this.lights[index];
  21578. }
  21579. }
  21580. return null;
  21581. };
  21582. Scene.prototype.getNodeByID = function (id) {
  21583. var mesh = this.getMeshByID(id);
  21584. if (mesh) {
  21585. return mesh;
  21586. }
  21587. var light = this.getLightByID(id);
  21588. if (light) {
  21589. return light;
  21590. }
  21591. var camera = this.getCameraByID(id);
  21592. if (camera) {
  21593. return camera;
  21594. }
  21595. var bone = this.getBoneByID(id);
  21596. return bone;
  21597. };
  21598. Scene.prototype.getNodeByName = function (name) {
  21599. var mesh = this.getMeshByName(name);
  21600. if (mesh) {
  21601. return mesh;
  21602. }
  21603. var light = this.getLightByName(name);
  21604. if (light) {
  21605. return light;
  21606. }
  21607. var camera = this.getCameraByName(name);
  21608. if (camera) {
  21609. return camera;
  21610. }
  21611. var bone = this.getBoneByName(name);
  21612. return bone;
  21613. };
  21614. Scene.prototype.getMeshByName = function (name) {
  21615. for (var index = 0; index < this.meshes.length; index++) {
  21616. if (this.meshes[index].name === name) {
  21617. return this.meshes[index];
  21618. }
  21619. }
  21620. return null;
  21621. };
  21622. Scene.prototype.getSoundByName = function (name) {
  21623. var index;
  21624. if (BABYLON.AudioEngine) {
  21625. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21626. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21627. return this.mainSoundTrack.soundCollection[index];
  21628. }
  21629. }
  21630. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21631. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21632. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21633. return this.soundTracks[sdIndex].soundCollection[index];
  21634. }
  21635. }
  21636. }
  21637. }
  21638. return null;
  21639. };
  21640. Scene.prototype.getLastSkeletonByID = function (id) {
  21641. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21642. if (this.skeletons[index].id === id) {
  21643. return this.skeletons[index];
  21644. }
  21645. }
  21646. return null;
  21647. };
  21648. Scene.prototype.getSkeletonById = function (id) {
  21649. for (var index = 0; index < this.skeletons.length; index++) {
  21650. if (this.skeletons[index].id === id) {
  21651. return this.skeletons[index];
  21652. }
  21653. }
  21654. return null;
  21655. };
  21656. Scene.prototype.getSkeletonByName = function (name) {
  21657. for (var index = 0; index < this.skeletons.length; index++) {
  21658. if (this.skeletons[index].name === name) {
  21659. return this.skeletons[index];
  21660. }
  21661. }
  21662. return null;
  21663. };
  21664. Scene.prototype.isActiveMesh = function (mesh) {
  21665. return (this._activeMeshes.indexOf(mesh) !== -1);
  21666. };
  21667. /**
  21668. * Return a the first highlight layer of the scene with a given name.
  21669. * @param name The name of the highlight layer to look for.
  21670. * @return The highlight layer if found otherwise null.
  21671. */
  21672. Scene.prototype.getHighlightLayerByName = function (name) {
  21673. for (var index = 0; index < this.highlightLayers.length; index++) {
  21674. if (this.highlightLayers[index].name === name) {
  21675. return this.highlightLayers[index];
  21676. }
  21677. }
  21678. return null;
  21679. };
  21680. Object.defineProperty(Scene.prototype, "uid", {
  21681. /**
  21682. * Return a unique id as a string which can serve as an identifier for the scene
  21683. */
  21684. get: function () {
  21685. if (!this._uid) {
  21686. this._uid = BABYLON.Tools.RandomId();
  21687. }
  21688. return this._uid;
  21689. },
  21690. enumerable: true,
  21691. configurable: true
  21692. });
  21693. /**
  21694. * Add an externaly attached data from its key.
  21695. * This method call will fail and return false, if such key already exists.
  21696. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21697. * @param key the unique key that identifies the data
  21698. * @param data the data object to associate to the key for this Engine instance
  21699. * @return true if no such key were already present and the data was added successfully, false otherwise
  21700. */
  21701. Scene.prototype.addExternalData = function (key, data) {
  21702. return this._externalData.add(key, data);
  21703. };
  21704. /**
  21705. * Get an externaly attached data from its key
  21706. * @param key the unique key that identifies the data
  21707. * @return the associated data, if present (can be null), or undefined if not present
  21708. */
  21709. Scene.prototype.getExternalData = function (key) {
  21710. return this._externalData.get(key);
  21711. };
  21712. /**
  21713. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21714. * @param key the unique key that identifies the data
  21715. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21716. * @return the associated data, can be null if the factory returned null.
  21717. */
  21718. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21719. return this._externalData.getOrAddWithFactory(key, factory);
  21720. };
  21721. /**
  21722. * Remove an externaly attached data from the Engine instance
  21723. * @param key the unique key that identifies the data
  21724. * @return true if the data was successfully removed, false if it doesn't exist
  21725. */
  21726. Scene.prototype.removeExternalData = function (key) {
  21727. return this._externalData.remove(key);
  21728. };
  21729. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21730. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21731. var material = subMesh.getMaterial();
  21732. if (mesh.showSubMeshesBoundingBox) {
  21733. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  21734. }
  21735. if (material) {
  21736. // Render targets
  21737. if (material.getRenderTargetTextures) {
  21738. if (this._processedMaterials.indexOf(material) === -1) {
  21739. this._processedMaterials.push(material);
  21740. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21741. }
  21742. }
  21743. // Dispatch
  21744. this._activeIndices.addCount(subMesh.indexCount, false);
  21745. this._renderingManager.dispatch(subMesh);
  21746. }
  21747. }
  21748. };
  21749. Scene.prototype._isInIntermediateRendering = function () {
  21750. return this._intermediateRendering;
  21751. };
  21752. Scene.prototype._evaluateActiveMeshes = function () {
  21753. this.activeCamera._activeMeshes.reset();
  21754. this._activeMeshes.reset();
  21755. this._renderingManager.reset();
  21756. this._processedMaterials.reset();
  21757. this._activeParticleSystems.reset();
  21758. this._activeSkeletons.reset();
  21759. this._softwareSkinnedMeshes.reset();
  21760. this._boundingBoxRenderer.reset();
  21761. this._edgesRenderers.reset();
  21762. // Meshes
  21763. var meshes;
  21764. var len;
  21765. if (this._selectionOctree) {
  21766. var selection = this._selectionOctree.select(this._frustumPlanes);
  21767. meshes = selection.data;
  21768. len = selection.length;
  21769. }
  21770. else {
  21771. len = this.meshes.length;
  21772. meshes = this.meshes;
  21773. }
  21774. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  21775. var mesh = meshes[meshIndex];
  21776. if (mesh.isBlocked) {
  21777. continue;
  21778. }
  21779. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21780. if (!mesh.isReady() || !mesh.isEnabled()) {
  21781. continue;
  21782. }
  21783. mesh.computeWorldMatrix();
  21784. // Intersections
  21785. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21786. this._meshesForIntersections.pushNoDuplicate(mesh);
  21787. }
  21788. // Switch to current LOD
  21789. var meshLOD = mesh.getLOD(this.activeCamera);
  21790. if (!meshLOD) {
  21791. continue;
  21792. }
  21793. mesh._preActivate();
  21794. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21795. this._activeMeshes.push(mesh);
  21796. this.activeCamera._activeMeshes.push(mesh);
  21797. mesh._activate(this._renderId);
  21798. this._activeMesh(mesh, meshLOD);
  21799. }
  21800. }
  21801. // Particle systems
  21802. this._particlesDuration.beginMonitoring();
  21803. var beforeParticlesDate = BABYLON.Tools.Now;
  21804. if (this.particlesEnabled) {
  21805. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  21806. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21807. var particleSystem = this.particleSystems[particleIndex];
  21808. if (!particleSystem.isStarted()) {
  21809. continue;
  21810. }
  21811. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  21812. this._activeParticleSystems.push(particleSystem);
  21813. particleSystem.animate();
  21814. this._renderingManager.dispatchParticles(particleSystem);
  21815. }
  21816. }
  21817. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  21818. }
  21819. this._particlesDuration.endMonitoring(false);
  21820. };
  21821. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21822. if (mesh.skeleton && this.skeletonsEnabled) {
  21823. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21824. mesh.skeleton.prepare();
  21825. }
  21826. if (!mesh.computeBonesUsingShaders) {
  21827. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21828. }
  21829. }
  21830. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21831. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  21832. }
  21833. if (sourceMesh._edgesRenderer) {
  21834. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  21835. }
  21836. if (mesh && mesh.subMeshes) {
  21837. // Submeshes Octrees
  21838. var len;
  21839. var subMeshes;
  21840. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  21841. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21842. len = intersections.length;
  21843. subMeshes = intersections.data;
  21844. }
  21845. else {
  21846. subMeshes = mesh.subMeshes;
  21847. len = subMeshes.length;
  21848. }
  21849. for (var subIndex = 0; subIndex < len; subIndex++) {
  21850. var subMesh = subMeshes[subIndex];
  21851. this._evaluateSubMesh(subMesh, mesh);
  21852. }
  21853. }
  21854. };
  21855. Scene.prototype.updateTransformMatrix = function (force) {
  21856. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21857. };
  21858. Scene.prototype._renderForCamera = function (camera) {
  21859. var engine = this._engine;
  21860. var startTime = BABYLON.Tools.Now;
  21861. this.activeCamera = camera;
  21862. if (!this.activeCamera)
  21863. throw new Error("Active camera not set");
  21864. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21865. // Viewport
  21866. engine.setViewport(this.activeCamera.viewport);
  21867. // Camera
  21868. this.resetCachedMaterial();
  21869. this._renderId++;
  21870. this.updateTransformMatrix();
  21871. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21872. // Meshes
  21873. this._evaluateActiveMeshesDuration.beginMonitoring();
  21874. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  21875. this._evaluateActiveMeshes();
  21876. this._evaluateActiveMeshesDuration.endMonitoring(false);
  21877. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  21878. // Software skinning
  21879. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21880. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21881. mesh.applySkeleton(mesh.skeleton);
  21882. }
  21883. // Render targets
  21884. this._renderTargetsDuration.beginMonitoring();
  21885. var needsRestoreFrameBuffer = false;
  21886. var beforeRenderTargetDate = BABYLON.Tools.Now;
  21887. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  21888. this._intermediateRendering = true;
  21889. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21890. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  21891. var renderTarget = this._renderTargets.data[renderIndex];
  21892. if (renderTarget._shouldRender()) {
  21893. this._renderId++;
  21894. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  21895. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  21896. }
  21897. }
  21898. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21899. this._intermediateRendering = false;
  21900. this._renderId++;
  21901. needsRestoreFrameBuffer = true; // Restore back buffer
  21902. }
  21903. // Render HighlightLayer Texture
  21904. var stencilState = this._engine.getStencilBuffer();
  21905. var renderhighlights = false;
  21906. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  21907. this._intermediateRendering = true;
  21908. for (var i = 0; i < this.highlightLayers.length; i++) {
  21909. var highlightLayer = this.highlightLayers[i];
  21910. if (highlightLayer.shouldRender() &&
  21911. (!highlightLayer.camera ||
  21912. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  21913. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  21914. renderhighlights = true;
  21915. var renderTarget = highlightLayer._mainTexture;
  21916. if (renderTarget._shouldRender()) {
  21917. this._renderId++;
  21918. renderTarget.render(false, false);
  21919. needsRestoreFrameBuffer = true;
  21920. }
  21921. }
  21922. }
  21923. this._intermediateRendering = false;
  21924. this._renderId++;
  21925. }
  21926. if (needsRestoreFrameBuffer) {
  21927. engine.restoreDefaultFramebuffer();
  21928. }
  21929. this._renderTargetsDuration.endMonitoring(false);
  21930. // Prepare Frame
  21931. this.postProcessManager._prepareFrame();
  21932. this._renderDuration.beginMonitoring();
  21933. // Backgrounds
  21934. var layerIndex;
  21935. var layer;
  21936. if (this.layers.length) {
  21937. engine.setDepthBuffer(false);
  21938. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21939. layer = this.layers[layerIndex];
  21940. if (layer.isBackground) {
  21941. layer.render();
  21942. }
  21943. }
  21944. engine.setDepthBuffer(true);
  21945. }
  21946. // Render
  21947. BABYLON.Tools.StartPerformanceCounter("Main render");
  21948. // Activate HighlightLayer stencil
  21949. if (renderhighlights) {
  21950. this._engine.setStencilBuffer(true);
  21951. }
  21952. this._renderingManager.render(null, null, true, true);
  21953. // Restore HighlightLayer stencil
  21954. if (renderhighlights) {
  21955. this._engine.setStencilBuffer(stencilState);
  21956. }
  21957. BABYLON.Tools.EndPerformanceCounter("Main render");
  21958. // Bounding boxes
  21959. this._boundingBoxRenderer.render();
  21960. // Edges
  21961. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21962. this._edgesRenderers.data[edgesRendererIndex].render();
  21963. }
  21964. // Lens flares
  21965. if (this.lensFlaresEnabled) {
  21966. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21967. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  21968. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  21969. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  21970. lensFlareSystem.render();
  21971. }
  21972. }
  21973. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21974. }
  21975. // Foregrounds
  21976. if (this.layers.length) {
  21977. engine.setDepthBuffer(false);
  21978. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21979. layer = this.layers[layerIndex];
  21980. if (!layer.isBackground) {
  21981. layer.render();
  21982. }
  21983. }
  21984. engine.setDepthBuffer(true);
  21985. }
  21986. // Highlight Layer
  21987. if (renderhighlights) {
  21988. engine.setDepthBuffer(false);
  21989. for (var i = 0; i < this.highlightLayers.length; i++) {
  21990. if (this.highlightLayers[i].shouldRender()) {
  21991. this.highlightLayers[i].render();
  21992. }
  21993. }
  21994. engine.setDepthBuffer(true);
  21995. }
  21996. this._renderDuration.endMonitoring(false);
  21997. // Finalize frame
  21998. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  21999. // Update camera
  22000. this.activeCamera._updateFromScene();
  22001. // Reset some special arrays
  22002. this._renderTargets.reset();
  22003. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22004. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22005. };
  22006. Scene.prototype._processSubCameras = function (camera) {
  22007. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22008. this._renderForCamera(camera);
  22009. return;
  22010. }
  22011. // rig cameras
  22012. for (var index = 0; index < camera._rigCameras.length; index++) {
  22013. this._renderForCamera(camera._rigCameras[index]);
  22014. }
  22015. this.activeCamera = camera;
  22016. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22017. // Update camera
  22018. this.activeCamera._updateFromScene();
  22019. };
  22020. Scene.prototype._checkIntersections = function () {
  22021. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22022. var sourceMesh = this._meshesForIntersections.data[index];
  22023. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22024. var action = sourceMesh.actionManager.actions[actionIndex];
  22025. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22026. var parameters = action.getTriggerParameter();
  22027. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22028. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22029. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22030. if (areIntersecting && currentIntersectionInProgress === -1) {
  22031. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22032. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  22033. sourceMesh._intersectionsInProgress.push(otherMesh);
  22034. }
  22035. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22036. sourceMesh._intersectionsInProgress.push(otherMesh);
  22037. }
  22038. }
  22039. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22040. //They intersected, and now they don't.
  22041. //is this trigger an exit trigger? execute an event.
  22042. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22043. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  22044. }
  22045. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22046. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22047. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22048. }
  22049. }
  22050. }
  22051. }
  22052. }
  22053. };
  22054. Scene.prototype.render = function () {
  22055. if (this.isDisposed) {
  22056. return;
  22057. }
  22058. this._lastFrameDuration.beginMonitoring();
  22059. this._particlesDuration.fetchNewFrame();
  22060. this._spritesDuration.fetchNewFrame();
  22061. this._activeParticles.fetchNewFrame();
  22062. this._renderDuration.fetchNewFrame();
  22063. this._renderTargetsDuration.fetchNewFrame();
  22064. this._evaluateActiveMeshesDuration.fetchNewFrame();
  22065. this._totalVertices.fetchNewFrame();
  22066. this._activeIndices.fetchNewFrame();
  22067. this._activeBones.fetchNewFrame();
  22068. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  22069. this._meshesForIntersections.reset();
  22070. this.resetCachedMaterial();
  22071. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  22072. // Actions
  22073. if (this.actionManager) {
  22074. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  22075. }
  22076. //Simplification Queue
  22077. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22078. this.simplificationQueue.executeNext();
  22079. }
  22080. // Animations
  22081. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22082. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22083. this._animate();
  22084. // Physics
  22085. if (this._physicsEngine) {
  22086. BABYLON.Tools.StartPerformanceCounter("Physics");
  22087. this._physicsEngine._step(deltaTime / 1000.0);
  22088. BABYLON.Tools.EndPerformanceCounter("Physics");
  22089. }
  22090. // Before render
  22091. this.onBeforeRenderObservable.notifyObservers(this);
  22092. // Customs render targets
  22093. this._renderTargetsDuration.beginMonitoring();
  22094. var beforeRenderTargetDate = BABYLON.Tools.Now;
  22095. var engine = this.getEngine();
  22096. var currentActiveCamera = this.activeCamera;
  22097. if (this.renderTargetsEnabled) {
  22098. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22099. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22100. var renderTarget = this.customRenderTargets[customIndex];
  22101. if (renderTarget._shouldRender()) {
  22102. this._renderId++;
  22103. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22104. if (!this.activeCamera)
  22105. throw new Error("Active camera not set");
  22106. // Viewport
  22107. engine.setViewport(this.activeCamera.viewport);
  22108. // Camera
  22109. this.updateTransformMatrix();
  22110. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22111. }
  22112. }
  22113. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22114. this._renderId++;
  22115. }
  22116. if (this.customRenderTargets.length > 0) {
  22117. engine.restoreDefaultFramebuffer();
  22118. }
  22119. this._renderTargetsDuration.endMonitoring();
  22120. this.activeCamera = currentActiveCamera;
  22121. // Procedural textures
  22122. if (this.proceduralTexturesEnabled) {
  22123. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22124. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22125. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22126. if (proceduralTexture._shouldRender()) {
  22127. proceduralTexture.render();
  22128. }
  22129. }
  22130. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22131. }
  22132. // Clear
  22133. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  22134. // Shadows
  22135. if (this.shadowsEnabled) {
  22136. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22137. var light = this.lights[lightIndex];
  22138. var shadowGenerator = light.getShadowGenerator();
  22139. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  22140. this._renderTargets.push(shadowGenerator.getShadowMap());
  22141. }
  22142. }
  22143. }
  22144. // Depth renderer
  22145. if (this._depthRenderer) {
  22146. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22147. }
  22148. // RenderPipeline
  22149. this.postProcessRenderPipelineManager.update();
  22150. // Multi-cameras?
  22151. if (this.activeCameras.length > 0) {
  22152. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22153. if (cameraIndex > 0) {
  22154. this._engine.clear(null, false, true, true);
  22155. }
  22156. this._processSubCameras(this.activeCameras[cameraIndex]);
  22157. }
  22158. }
  22159. else {
  22160. if (!this.activeCamera) {
  22161. throw new Error("No camera defined");
  22162. }
  22163. this._processSubCameras(this.activeCamera);
  22164. }
  22165. // Intersection checks
  22166. this._checkIntersections();
  22167. // Update the audio listener attached to the camera
  22168. if (BABYLON.AudioEngine) {
  22169. this._updateAudioParameters();
  22170. }
  22171. // After render
  22172. if (this.afterRender) {
  22173. this.afterRender();
  22174. }
  22175. this.onAfterRenderObservable.notifyObservers(this);
  22176. // Cleaning
  22177. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22178. this._toBeDisposed.data[index].dispose();
  22179. this._toBeDisposed[index] = null;
  22180. }
  22181. this._toBeDisposed.reset();
  22182. if (this.dumpNextRenderTargets) {
  22183. this.dumpNextRenderTargets = false;
  22184. }
  22185. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  22186. this._lastFrameDuration.endMonitoring();
  22187. this._totalMeshesCounter.addCount(this.meshes.length, true);
  22188. this._totalLightsCounter.addCount(this.lights.length, true);
  22189. this._totalMaterialsCounter.addCount(this.materials.length, true);
  22190. this._totalTexturesCounter.addCount(this.textures.length, true);
  22191. this._activeBones.addCount(0, true);
  22192. this._activeIndices.addCount(0, true);
  22193. this._activeParticles.addCount(0, true);
  22194. };
  22195. Scene.prototype._updateAudioParameters = function () {
  22196. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22197. return;
  22198. }
  22199. var listeningCamera;
  22200. var audioEngine = BABYLON.Engine.audioEngine;
  22201. if (this.activeCameras.length > 0) {
  22202. listeningCamera = this.activeCameras[0];
  22203. }
  22204. else {
  22205. listeningCamera = this.activeCamera;
  22206. }
  22207. if (listeningCamera && audioEngine.canUseWebAudio) {
  22208. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22209. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22210. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22211. cameraDirection.normalize();
  22212. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22213. var i;
  22214. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22215. var sound = this.mainSoundTrack.soundCollection[i];
  22216. if (sound.useCustomAttenuation) {
  22217. sound.updateDistanceFromListener();
  22218. }
  22219. }
  22220. for (i = 0; i < this.soundTracks.length; i++) {
  22221. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22222. sound = this.soundTracks[i].soundCollection[j];
  22223. if (sound.useCustomAttenuation) {
  22224. sound.updateDistanceFromListener();
  22225. }
  22226. }
  22227. }
  22228. }
  22229. };
  22230. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22231. // Audio
  22232. get: function () {
  22233. return this._audioEnabled;
  22234. },
  22235. set: function (value) {
  22236. this._audioEnabled = value;
  22237. if (BABYLON.AudioEngine) {
  22238. if (this._audioEnabled) {
  22239. this._enableAudio();
  22240. }
  22241. else {
  22242. this._disableAudio();
  22243. }
  22244. }
  22245. },
  22246. enumerable: true,
  22247. configurable: true
  22248. });
  22249. Scene.prototype._disableAudio = function () {
  22250. var i;
  22251. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22252. this.mainSoundTrack.soundCollection[i].pause();
  22253. }
  22254. for (i = 0; i < this.soundTracks.length; i++) {
  22255. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22256. this.soundTracks[i].soundCollection[j].pause();
  22257. }
  22258. }
  22259. };
  22260. Scene.prototype._enableAudio = function () {
  22261. var i;
  22262. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22263. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22264. this.mainSoundTrack.soundCollection[i].play();
  22265. }
  22266. }
  22267. for (i = 0; i < this.soundTracks.length; i++) {
  22268. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22269. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22270. this.soundTracks[i].soundCollection[j].play();
  22271. }
  22272. }
  22273. }
  22274. };
  22275. Object.defineProperty(Scene.prototype, "headphone", {
  22276. get: function () {
  22277. return this._headphone;
  22278. },
  22279. set: function (value) {
  22280. this._headphone = value;
  22281. if (BABYLON.AudioEngine) {
  22282. if (this._headphone) {
  22283. this._switchAudioModeForHeadphones();
  22284. }
  22285. else {
  22286. this._switchAudioModeForNormalSpeakers();
  22287. }
  22288. }
  22289. },
  22290. enumerable: true,
  22291. configurable: true
  22292. });
  22293. Scene.prototype._switchAudioModeForHeadphones = function () {
  22294. this.mainSoundTrack.switchPanningModelToHRTF();
  22295. for (var i = 0; i < this.soundTracks.length; i++) {
  22296. this.soundTracks[i].switchPanningModelToHRTF();
  22297. }
  22298. };
  22299. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22300. this.mainSoundTrack.switchPanningModelToEqualPower();
  22301. for (var i = 0; i < this.soundTracks.length; i++) {
  22302. this.soundTracks[i].switchPanningModelToEqualPower();
  22303. }
  22304. };
  22305. Scene.prototype.enableDepthRenderer = function () {
  22306. if (this._depthRenderer) {
  22307. return this._depthRenderer;
  22308. }
  22309. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22310. return this._depthRenderer;
  22311. };
  22312. Scene.prototype.disableDepthRenderer = function () {
  22313. if (!this._depthRenderer) {
  22314. return;
  22315. }
  22316. this._depthRenderer.dispose();
  22317. this._depthRenderer = null;
  22318. };
  22319. Scene.prototype.freezeMaterials = function () {
  22320. for (var i = 0; i < this.materials.length; i++) {
  22321. this.materials[i].freeze();
  22322. }
  22323. };
  22324. Scene.prototype.unfreezeMaterials = function () {
  22325. for (var i = 0; i < this.materials.length; i++) {
  22326. this.materials[i].unfreeze();
  22327. }
  22328. };
  22329. Scene.prototype.dispose = function () {
  22330. this.beforeRender = null;
  22331. this.afterRender = null;
  22332. this.skeletons = [];
  22333. this._boundingBoxRenderer.dispose();
  22334. if (this._depthRenderer) {
  22335. this._depthRenderer.dispose();
  22336. }
  22337. // Smart arrays
  22338. if (this.activeCamera) {
  22339. this.activeCamera._activeMeshes.dispose();
  22340. this.activeCamera = null;
  22341. }
  22342. this._activeMeshes.dispose();
  22343. this._renderingManager.dispose();
  22344. this._processedMaterials.dispose();
  22345. this._activeParticleSystems.dispose();
  22346. this._activeSkeletons.dispose();
  22347. this._softwareSkinnedMeshes.dispose();
  22348. this._boundingBoxRenderer.dispose();
  22349. this._edgesRenderers.dispose();
  22350. this._meshesForIntersections.dispose();
  22351. this._toBeDisposed.dispose();
  22352. // Debug layer
  22353. if (this._debugLayer) {
  22354. this._debugLayer.hide();
  22355. }
  22356. // Events
  22357. this.onDisposeObservable.notifyObservers(this);
  22358. this.onDisposeObservable.clear();
  22359. this.onBeforeRenderObservable.clear();
  22360. this.onAfterRenderObservable.clear();
  22361. this.detachControl();
  22362. // Release sounds & sounds tracks
  22363. if (BABYLON.AudioEngine) {
  22364. this.disposeSounds();
  22365. }
  22366. // Detach cameras
  22367. var canvas = this._engine.getRenderingCanvas();
  22368. var index;
  22369. for (index = 0; index < this.cameras.length; index++) {
  22370. this.cameras[index].detachControl(canvas);
  22371. }
  22372. // Release lights
  22373. while (this.lights.length) {
  22374. this.lights[0].dispose();
  22375. }
  22376. // Release meshes
  22377. while (this.meshes.length) {
  22378. this.meshes[0].dispose(true);
  22379. }
  22380. // Release cameras
  22381. while (this.cameras.length) {
  22382. this.cameras[0].dispose();
  22383. }
  22384. // Release materials
  22385. while (this.materials.length) {
  22386. this.materials[0].dispose();
  22387. }
  22388. // Release particles
  22389. while (this.particleSystems.length) {
  22390. this.particleSystems[0].dispose();
  22391. }
  22392. // Release sprites
  22393. while (this.spriteManagers.length) {
  22394. this.spriteManagers[0].dispose();
  22395. }
  22396. // Release layers
  22397. while (this.layers.length) {
  22398. this.layers[0].dispose();
  22399. }
  22400. while (this.highlightLayers.length) {
  22401. this.highlightLayers[0].dispose();
  22402. }
  22403. // Release textures
  22404. while (this.textures.length) {
  22405. this.textures[0].dispose();
  22406. }
  22407. // Post-processes
  22408. this.postProcessManager.dispose();
  22409. // Physics
  22410. if (this._physicsEngine) {
  22411. this.disablePhysicsEngine();
  22412. }
  22413. // Remove from engine
  22414. index = this._engine.scenes.indexOf(this);
  22415. if (index > -1) {
  22416. this._engine.scenes.splice(index, 1);
  22417. }
  22418. this._engine.wipeCaches();
  22419. this._engine = null;
  22420. };
  22421. Object.defineProperty(Scene.prototype, "isDisposed", {
  22422. get: function () {
  22423. return !this._engine;
  22424. },
  22425. enumerable: true,
  22426. configurable: true
  22427. });
  22428. // Release sounds & sounds tracks
  22429. Scene.prototype.disposeSounds = function () {
  22430. this.mainSoundTrack.dispose();
  22431. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22432. this.soundTracks[scIndex].dispose();
  22433. }
  22434. };
  22435. // Octrees
  22436. Scene.prototype.getWorldExtends = function () {
  22437. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22438. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22439. for (var index = 0; index < this.meshes.length; index++) {
  22440. var mesh = this.meshes[index];
  22441. mesh.computeWorldMatrix(true);
  22442. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  22443. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  22444. BABYLON.Tools.CheckExtends(minBox, min, max);
  22445. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22446. }
  22447. return {
  22448. min: min,
  22449. max: max
  22450. };
  22451. };
  22452. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22453. if (maxCapacity === void 0) { maxCapacity = 64; }
  22454. if (maxDepth === void 0) { maxDepth = 2; }
  22455. if (!this._selectionOctree) {
  22456. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  22457. }
  22458. var worldExtends = this.getWorldExtends();
  22459. // Update octree
  22460. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  22461. return this._selectionOctree;
  22462. };
  22463. // Picking
  22464. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  22465. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22466. var engine = this._engine;
  22467. if (!camera) {
  22468. if (!this.activeCamera)
  22469. throw new Error("Active camera not set");
  22470. camera = this.activeCamera;
  22471. }
  22472. var cameraViewport = camera.viewport;
  22473. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22474. // Moving coordinates to local viewport world
  22475. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22476. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22477. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  22478. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  22479. };
  22480. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22481. var engine = this._engine;
  22482. if (!camera) {
  22483. if (!this.activeCamera)
  22484. throw new Error("Active camera not set");
  22485. camera = this.activeCamera;
  22486. }
  22487. var cameraViewport = camera.viewport;
  22488. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22489. var identity = BABYLON.Matrix.Identity();
  22490. // Moving coordinates to local viewport world
  22491. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22492. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22493. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22494. };
  22495. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22496. var pickingInfo = null;
  22497. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22498. var mesh = this.meshes[meshIndex];
  22499. if (predicate) {
  22500. if (!predicate(mesh)) {
  22501. continue;
  22502. }
  22503. }
  22504. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22505. continue;
  22506. }
  22507. var world = mesh.getWorldMatrix();
  22508. var ray = rayFunction(world);
  22509. var result = mesh.intersects(ray, fastCheck);
  22510. if (!result || !result.hit)
  22511. continue;
  22512. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22513. continue;
  22514. pickingInfo = result;
  22515. if (fastCheck) {
  22516. break;
  22517. }
  22518. }
  22519. return pickingInfo || new BABYLON.PickingInfo();
  22520. };
  22521. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22522. var pickingInfos = new Array();
  22523. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22524. var mesh = this.meshes[meshIndex];
  22525. if (predicate) {
  22526. if (!predicate(mesh)) {
  22527. continue;
  22528. }
  22529. }
  22530. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22531. continue;
  22532. }
  22533. var world = mesh.getWorldMatrix();
  22534. var ray = rayFunction(world);
  22535. var result = mesh.intersects(ray, false);
  22536. if (!result || !result.hit)
  22537. continue;
  22538. pickingInfos.push(result);
  22539. }
  22540. return pickingInfos;
  22541. };
  22542. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22543. var pickingInfo = null;
  22544. camera = camera || this.activeCamera;
  22545. if (this.spriteManagers.length > 0) {
  22546. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22547. var spriteManager = this.spriteManagers[spriteIndex];
  22548. if (!spriteManager.isPickable) {
  22549. continue;
  22550. }
  22551. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22552. if (!result || !result.hit)
  22553. continue;
  22554. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22555. continue;
  22556. pickingInfo = result;
  22557. if (fastCheck) {
  22558. break;
  22559. }
  22560. }
  22561. }
  22562. return pickingInfo || new BABYLON.PickingInfo();
  22563. };
  22564. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22565. /// <param name="x">X position on screen</param>
  22566. /// <param name="y">Y position on screen</param>
  22567. /// <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>
  22568. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  22569. /// <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>
  22570. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22571. var _this = this;
  22572. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  22573. };
  22574. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22575. /// <param name="x">X position on screen</param>
  22576. /// <param name="y">Y position on screen</param>
  22577. /// <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>
  22578. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  22579. /// <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>
  22580. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22581. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  22582. };
  22583. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22584. var _this = this;
  22585. return this._internalPick(function (world) {
  22586. if (!_this._pickWithRayInverseMatrix) {
  22587. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22588. }
  22589. world.invertToRef(_this._pickWithRayInverseMatrix);
  22590. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  22591. }, predicate, fastCheck);
  22592. };
  22593. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22594. /// <param name="x">X position on screen</param>
  22595. /// <param name="y">Y position on screen</param>
  22596. /// <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>
  22597. /// <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>
  22598. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22599. var _this = this;
  22600. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  22601. };
  22602. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22603. /// <param name="ray">Ray to use</param>
  22604. /// <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>
  22605. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22606. var _this = this;
  22607. return this._internalMultiPick(function (world) {
  22608. if (!_this._pickWithRayInverseMatrix) {
  22609. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22610. }
  22611. world.invertToRef(_this._pickWithRayInverseMatrix);
  22612. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  22613. }, predicate);
  22614. };
  22615. Scene.prototype.setPointerOverMesh = function (mesh) {
  22616. if (this._pointerOverMesh === mesh) {
  22617. return;
  22618. }
  22619. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22620. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22621. }
  22622. this._pointerOverMesh = mesh;
  22623. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22624. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22625. }
  22626. };
  22627. Scene.prototype.getPointerOverMesh = function () {
  22628. return this._pointerOverMesh;
  22629. };
  22630. Scene.prototype.setPointerOverSprite = function (sprite) {
  22631. if (this._pointerOverSprite === sprite) {
  22632. return;
  22633. }
  22634. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22635. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22636. }
  22637. this._pointerOverSprite = sprite;
  22638. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22639. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22640. }
  22641. };
  22642. Scene.prototype.getPointerOverSprite = function () {
  22643. return this._pointerOverSprite;
  22644. };
  22645. // Physics
  22646. Scene.prototype.getPhysicsEngine = function () {
  22647. return this._physicsEngine;
  22648. };
  22649. /**
  22650. * Enables physics to the current scene
  22651. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22652. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22653. * @return {boolean} was the physics engine initialized
  22654. */
  22655. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22656. if (this._physicsEngine) {
  22657. return true;
  22658. }
  22659. try {
  22660. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22661. return true;
  22662. }
  22663. catch (e) {
  22664. BABYLON.Tools.Error(e.message);
  22665. return false;
  22666. }
  22667. };
  22668. Scene.prototype.disablePhysicsEngine = function () {
  22669. if (!this._physicsEngine) {
  22670. return;
  22671. }
  22672. this._physicsEngine.dispose();
  22673. this._physicsEngine = undefined;
  22674. };
  22675. Scene.prototype.isPhysicsEnabled = function () {
  22676. return this._physicsEngine !== undefined;
  22677. };
  22678. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22679. var mesh = compound.parts[0].mesh;
  22680. mesh.physicsImpostor.dispose();
  22681. mesh.physicsImpostor = null;
  22682. };
  22683. // Misc.
  22684. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  22685. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  22686. // Light
  22687. if (this.lights.length === 0) {
  22688. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  22689. }
  22690. // Camera
  22691. if (!this.activeCamera) {
  22692. // Compute position
  22693. var worldExtends = this.getWorldExtends();
  22694. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  22695. var camera;
  22696. if (createArcRotateCamera) {
  22697. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  22698. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  22699. camera.setTarget(worldCenter);
  22700. }
  22701. else {
  22702. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  22703. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  22704. camera.setTarget(worldCenter);
  22705. }
  22706. this.activeCamera = camera;
  22707. }
  22708. };
  22709. // Tags
  22710. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  22711. if (tagsQuery === undefined) {
  22712. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  22713. return list;
  22714. }
  22715. var listByTags = [];
  22716. forEach = forEach || (function (item) { return; });
  22717. for (var i in list) {
  22718. var item = list[i];
  22719. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  22720. listByTags.push(item);
  22721. forEach(item);
  22722. }
  22723. }
  22724. return listByTags;
  22725. };
  22726. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  22727. return this._getByTags(this.meshes, tagsQuery, forEach);
  22728. };
  22729. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  22730. return this._getByTags(this.cameras, tagsQuery, forEach);
  22731. };
  22732. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  22733. return this._getByTags(this.lights, tagsQuery, forEach);
  22734. };
  22735. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  22736. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  22737. };
  22738. /**
  22739. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22740. * This allowed control for front to back rendering or reversly depending of the special needs.
  22741. *
  22742. * @param renderingGroupId The rendering group id corresponding to its index
  22743. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22744. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22745. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22746. */
  22747. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22748. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22749. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22750. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22751. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  22752. };
  22753. /**
  22754. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22755. *
  22756. * @param renderingGroupId The rendering group id corresponding to its index
  22757. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22758. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22759. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22760. */
  22761. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22762. if (depth === void 0) { depth = true; }
  22763. if (stencil === void 0) { stencil = true; }
  22764. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  22765. };
  22766. /**
  22767. * Will flag all materials as dirty to trigger new shader compilation
  22768. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  22769. */
  22770. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  22771. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  22772. var material = _a[_i];
  22773. if (predicate && !predicate(material)) {
  22774. continue;
  22775. }
  22776. material.markAsDirty(flag);
  22777. }
  22778. };
  22779. return Scene;
  22780. }());
  22781. // Statics
  22782. Scene._FOGMODE_NONE = 0;
  22783. Scene._FOGMODE_EXP = 1;
  22784. Scene._FOGMODE_EXP2 = 2;
  22785. Scene._FOGMODE_LINEAR = 3;
  22786. Scene.MinDeltaTime = 1.0;
  22787. Scene.MaxDeltaTime = 1000.0;
  22788. Scene.DragMovementThreshold = 10; // in pixels
  22789. Scene.LongPressDelay = 500; // in milliseconds
  22790. Scene.DoubleClickDelay = 300; // in milliseconds
  22791. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  22792. BABYLON.Scene = Scene;
  22793. })(BABYLON || (BABYLON = {}));
  22794. //# sourceMappingURL=babylon.scene.js.map
  22795. var BABYLON;
  22796. (function (BABYLON) {
  22797. var Buffer = (function () {
  22798. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  22799. if (engine instanceof BABYLON.Mesh) {
  22800. this._engine = engine.getScene().getEngine();
  22801. }
  22802. else {
  22803. this._engine = engine;
  22804. }
  22805. this._updatable = updatable;
  22806. this._data = data;
  22807. this._strideSize = stride;
  22808. if (!postponeInternalCreation) {
  22809. this.create();
  22810. }
  22811. this._instanced = instanced;
  22812. }
  22813. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  22814. // a lot of these parameters are ignored as they are overriden by the buffer
  22815. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  22816. };
  22817. // Properties
  22818. Buffer.prototype.isUpdatable = function () {
  22819. return this._updatable;
  22820. };
  22821. Buffer.prototype.getData = function () {
  22822. return this._data;
  22823. };
  22824. Buffer.prototype.getBuffer = function () {
  22825. return this._buffer;
  22826. };
  22827. Buffer.prototype.getStrideSize = function () {
  22828. return this._strideSize;
  22829. };
  22830. Buffer.prototype.getIsInstanced = function () {
  22831. return this._instanced;
  22832. };
  22833. // Methods
  22834. Buffer.prototype.create = function (data) {
  22835. if (!data && this._buffer) {
  22836. return; // nothing to do
  22837. }
  22838. data = data || this._data;
  22839. if (!this._buffer) {
  22840. if (this._updatable) {
  22841. this._buffer = this._engine.createDynamicVertexBuffer(data);
  22842. this._data = data;
  22843. }
  22844. else {
  22845. this._buffer = this._engine.createVertexBuffer(data);
  22846. }
  22847. }
  22848. else if (this._updatable) {
  22849. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  22850. this._data = data;
  22851. }
  22852. };
  22853. Buffer.prototype.update = function (data) {
  22854. this.create(data);
  22855. };
  22856. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  22857. if (!this._buffer) {
  22858. return;
  22859. }
  22860. if (this._updatable) {
  22861. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  22862. this._data = null;
  22863. }
  22864. };
  22865. Buffer.prototype.dispose = function () {
  22866. if (!this._buffer) {
  22867. return;
  22868. }
  22869. if (this._engine._releaseBuffer(this._buffer)) {
  22870. this._buffer = null;
  22871. }
  22872. };
  22873. return Buffer;
  22874. }());
  22875. BABYLON.Buffer = Buffer;
  22876. })(BABYLON || (BABYLON = {}));
  22877. //# sourceMappingURL=babylon.buffer.js.map
  22878. var BABYLON;
  22879. (function (BABYLON) {
  22880. var VertexBuffer = (function () {
  22881. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  22882. if (!stride) {
  22883. // Deduce stride from kind
  22884. switch (kind) {
  22885. case VertexBuffer.PositionKind:
  22886. stride = 3;
  22887. break;
  22888. case VertexBuffer.NormalKind:
  22889. stride = 3;
  22890. break;
  22891. case VertexBuffer.UVKind:
  22892. case VertexBuffer.UV2Kind:
  22893. case VertexBuffer.UV3Kind:
  22894. case VertexBuffer.UV4Kind:
  22895. case VertexBuffer.UV5Kind:
  22896. case VertexBuffer.UV6Kind:
  22897. stride = 2;
  22898. break;
  22899. case VertexBuffer.TangentKind:
  22900. case VertexBuffer.ColorKind:
  22901. stride = 4;
  22902. break;
  22903. case VertexBuffer.MatricesIndicesKind:
  22904. case VertexBuffer.MatricesIndicesExtraKind:
  22905. stride = 4;
  22906. break;
  22907. case VertexBuffer.MatricesWeightsKind:
  22908. case VertexBuffer.MatricesWeightsExtraKind:
  22909. stride = 4;
  22910. break;
  22911. }
  22912. }
  22913. if (data instanceof BABYLON.Buffer) {
  22914. if (!stride) {
  22915. stride = data.getStrideSize();
  22916. }
  22917. this._buffer = data;
  22918. this._ownsBuffer = false;
  22919. }
  22920. else {
  22921. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  22922. this._ownsBuffer = true;
  22923. }
  22924. this._stride = stride;
  22925. this._offset = offset ? offset : 0;
  22926. this._size = size ? size : stride;
  22927. this._kind = kind;
  22928. }
  22929. /**
  22930. * Returns the kind of the VertexBuffer (string).
  22931. */
  22932. VertexBuffer.prototype.getKind = function () {
  22933. return this._kind;
  22934. };
  22935. // Properties
  22936. /**
  22937. * Boolean : is the VertexBuffer updatable ?
  22938. */
  22939. VertexBuffer.prototype.isUpdatable = function () {
  22940. return this._buffer.isUpdatable();
  22941. };
  22942. /**
  22943. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  22944. */
  22945. VertexBuffer.prototype.getData = function () {
  22946. return this._buffer.getData();
  22947. };
  22948. /**
  22949. * Returns the WebGLBuffer associated to the VertexBuffer.
  22950. */
  22951. VertexBuffer.prototype.getBuffer = function () {
  22952. return this._buffer.getBuffer();
  22953. };
  22954. /**
  22955. * Returns the stride of the VertexBuffer (integer).
  22956. */
  22957. VertexBuffer.prototype.getStrideSize = function () {
  22958. return this._stride;
  22959. };
  22960. /**
  22961. * Returns the offset (integer).
  22962. */
  22963. VertexBuffer.prototype.getOffset = function () {
  22964. return this._offset;
  22965. };
  22966. /**
  22967. * Returns the VertexBuffer total size (integer).
  22968. */
  22969. VertexBuffer.prototype.getSize = function () {
  22970. return this._size;
  22971. };
  22972. /**
  22973. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  22974. */
  22975. VertexBuffer.prototype.getIsInstanced = function () {
  22976. return this._buffer.getIsInstanced();
  22977. };
  22978. // Methods
  22979. /**
  22980. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  22981. * Returns the created WebGLBuffer.
  22982. */
  22983. VertexBuffer.prototype.create = function (data) {
  22984. return this._buffer.create(data);
  22985. };
  22986. /**
  22987. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22988. * Returns the updated WebGLBuffer.
  22989. */
  22990. VertexBuffer.prototype.update = function (data) {
  22991. return this._buffer.update(data);
  22992. };
  22993. /**
  22994. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22995. * Returns the directly updated WebGLBuffer.
  22996. */
  22997. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  22998. return this._buffer.updateDirectly(data, offset);
  22999. };
  23000. /**
  23001. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  23002. */
  23003. VertexBuffer.prototype.dispose = function () {
  23004. if (this._ownsBuffer) {
  23005. this._buffer.dispose();
  23006. }
  23007. };
  23008. Object.defineProperty(VertexBuffer, "PositionKind", {
  23009. get: function () {
  23010. return VertexBuffer._PositionKind;
  23011. },
  23012. enumerable: true,
  23013. configurable: true
  23014. });
  23015. Object.defineProperty(VertexBuffer, "NormalKind", {
  23016. get: function () {
  23017. return VertexBuffer._NormalKind;
  23018. },
  23019. enumerable: true,
  23020. configurable: true
  23021. });
  23022. Object.defineProperty(VertexBuffer, "TangentKind", {
  23023. get: function () {
  23024. return VertexBuffer._TangentKind;
  23025. },
  23026. enumerable: true,
  23027. configurable: true
  23028. });
  23029. Object.defineProperty(VertexBuffer, "UVKind", {
  23030. get: function () {
  23031. return VertexBuffer._UVKind;
  23032. },
  23033. enumerable: true,
  23034. configurable: true
  23035. });
  23036. Object.defineProperty(VertexBuffer, "UV2Kind", {
  23037. get: function () {
  23038. return VertexBuffer._UV2Kind;
  23039. },
  23040. enumerable: true,
  23041. configurable: true
  23042. });
  23043. Object.defineProperty(VertexBuffer, "UV3Kind", {
  23044. get: function () {
  23045. return VertexBuffer._UV3Kind;
  23046. },
  23047. enumerable: true,
  23048. configurable: true
  23049. });
  23050. Object.defineProperty(VertexBuffer, "UV4Kind", {
  23051. get: function () {
  23052. return VertexBuffer._UV4Kind;
  23053. },
  23054. enumerable: true,
  23055. configurable: true
  23056. });
  23057. Object.defineProperty(VertexBuffer, "UV5Kind", {
  23058. get: function () {
  23059. return VertexBuffer._UV5Kind;
  23060. },
  23061. enumerable: true,
  23062. configurable: true
  23063. });
  23064. Object.defineProperty(VertexBuffer, "UV6Kind", {
  23065. get: function () {
  23066. return VertexBuffer._UV6Kind;
  23067. },
  23068. enumerable: true,
  23069. configurable: true
  23070. });
  23071. Object.defineProperty(VertexBuffer, "ColorKind", {
  23072. get: function () {
  23073. return VertexBuffer._ColorKind;
  23074. },
  23075. enumerable: true,
  23076. configurable: true
  23077. });
  23078. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  23079. get: function () {
  23080. return VertexBuffer._MatricesIndicesKind;
  23081. },
  23082. enumerable: true,
  23083. configurable: true
  23084. });
  23085. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  23086. get: function () {
  23087. return VertexBuffer._MatricesWeightsKind;
  23088. },
  23089. enumerable: true,
  23090. configurable: true
  23091. });
  23092. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  23093. get: function () {
  23094. return VertexBuffer._MatricesIndicesExtraKind;
  23095. },
  23096. enumerable: true,
  23097. configurable: true
  23098. });
  23099. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  23100. get: function () {
  23101. return VertexBuffer._MatricesWeightsExtraKind;
  23102. },
  23103. enumerable: true,
  23104. configurable: true
  23105. });
  23106. return VertexBuffer;
  23107. }());
  23108. // Enums
  23109. VertexBuffer._PositionKind = "position";
  23110. VertexBuffer._NormalKind = "normal";
  23111. VertexBuffer._TangentKind = "tangent";
  23112. VertexBuffer._UVKind = "uv";
  23113. VertexBuffer._UV2Kind = "uv2";
  23114. VertexBuffer._UV3Kind = "uv3";
  23115. VertexBuffer._UV4Kind = "uv4";
  23116. VertexBuffer._UV5Kind = "uv5";
  23117. VertexBuffer._UV6Kind = "uv6";
  23118. VertexBuffer._ColorKind = "color";
  23119. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  23120. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  23121. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  23122. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  23123. BABYLON.VertexBuffer = VertexBuffer;
  23124. })(BABYLON || (BABYLON = {}));
  23125. //# sourceMappingURL=babylon.vertexBuffer.js.map
  23126. var BABYLON;
  23127. (function (BABYLON) {
  23128. /**
  23129. * Creates an instance based on a source mesh.
  23130. */
  23131. var InstancedMesh = (function (_super) {
  23132. __extends(InstancedMesh, _super);
  23133. function InstancedMesh(name, source) {
  23134. var _this = _super.call(this, name, source.getScene()) || this;
  23135. source.instances.push(_this);
  23136. _this._sourceMesh = source;
  23137. _this.position.copyFrom(source.position);
  23138. _this.rotation.copyFrom(source.rotation);
  23139. _this.scaling.copyFrom(source.scaling);
  23140. if (source.rotationQuaternion) {
  23141. _this.rotationQuaternion = source.rotationQuaternion.clone();
  23142. }
  23143. _this.infiniteDistance = source.infiniteDistance;
  23144. _this.setPivotMatrix(source.getPivotMatrix());
  23145. _this.refreshBoundingInfo();
  23146. _this._syncSubMeshes();
  23147. return _this;
  23148. }
  23149. /**
  23150. * Returns the string "InstancedMesh".
  23151. */
  23152. InstancedMesh.prototype.getClassName = function () {
  23153. return "InstancedMesh";
  23154. };
  23155. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  23156. // Methods
  23157. get: function () {
  23158. return this._sourceMesh.receiveShadows;
  23159. },
  23160. enumerable: true,
  23161. configurable: true
  23162. });
  23163. Object.defineProperty(InstancedMesh.prototype, "material", {
  23164. get: function () {
  23165. return this._sourceMesh.material;
  23166. },
  23167. enumerable: true,
  23168. configurable: true
  23169. });
  23170. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  23171. get: function () {
  23172. return this._sourceMesh.visibility;
  23173. },
  23174. enumerable: true,
  23175. configurable: true
  23176. });
  23177. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  23178. get: function () {
  23179. return this._sourceMesh.skeleton;
  23180. },
  23181. enumerable: true,
  23182. configurable: true
  23183. });
  23184. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  23185. get: function () {
  23186. return this._sourceMesh.renderingGroupId;
  23187. },
  23188. enumerable: true,
  23189. configurable: true
  23190. });
  23191. /**
  23192. * Returns the total number of vertices (integer).
  23193. */
  23194. InstancedMesh.prototype.getTotalVertices = function () {
  23195. return this._sourceMesh.getTotalVertices();
  23196. };
  23197. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  23198. get: function () {
  23199. return this._sourceMesh;
  23200. },
  23201. enumerable: true,
  23202. configurable: true
  23203. });
  23204. /**
  23205. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  23206. */
  23207. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  23208. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  23209. };
  23210. /**
  23211. * Boolean : True if the mesh owns the requested kind of data.
  23212. */
  23213. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  23214. return this._sourceMesh.isVerticesDataPresent(kind);
  23215. };
  23216. /**
  23217. * Returns an array of indices (IndicesArray).
  23218. */
  23219. InstancedMesh.prototype.getIndices = function () {
  23220. return this._sourceMesh.getIndices();
  23221. };
  23222. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  23223. get: function () {
  23224. return this._sourceMesh._positions;
  23225. },
  23226. enumerable: true,
  23227. configurable: true
  23228. });
  23229. /**
  23230. * Sets a new updated BoundingInfo to the mesh.
  23231. * Returns the mesh.
  23232. */
  23233. InstancedMesh.prototype.refreshBoundingInfo = function () {
  23234. var meshBB = this._sourceMesh.getBoundingInfo();
  23235. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  23236. this._updateBoundingInfo();
  23237. return this;
  23238. };
  23239. InstancedMesh.prototype._preActivate = function () {
  23240. if (this._currentLOD) {
  23241. this._currentLOD._preActivate();
  23242. }
  23243. return this;
  23244. };
  23245. InstancedMesh.prototype._activate = function (renderId) {
  23246. if (this._currentLOD) {
  23247. this._currentLOD._registerInstanceForRenderId(this, renderId);
  23248. }
  23249. return this;
  23250. };
  23251. /**
  23252. * Returns the current associated LOD AbstractMesh.
  23253. */
  23254. InstancedMesh.prototype.getLOD = function (camera) {
  23255. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  23256. if (this._currentLOD === this.sourceMesh) {
  23257. return this;
  23258. }
  23259. return this._currentLOD;
  23260. };
  23261. InstancedMesh.prototype._syncSubMeshes = function () {
  23262. this.releaseSubMeshes();
  23263. if (this._sourceMesh.subMeshes) {
  23264. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  23265. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  23266. }
  23267. }
  23268. return this;
  23269. };
  23270. InstancedMesh.prototype._generatePointsArray = function () {
  23271. return this._sourceMesh._generatePointsArray();
  23272. };
  23273. /**
  23274. * Creates a new InstancedMesh from the current mesh.
  23275. * - name (string) : the cloned mesh name
  23276. * - newParent (optional Node) : the optional Node to parent the clone to.
  23277. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  23278. *
  23279. * Returns the clone.
  23280. */
  23281. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  23282. var result = this._sourceMesh.createInstance(name);
  23283. // Deep copy
  23284. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  23285. // Bounding info
  23286. this.refreshBoundingInfo();
  23287. // Parent
  23288. if (newParent) {
  23289. result.parent = newParent;
  23290. }
  23291. if (!doNotCloneChildren) {
  23292. // Children
  23293. for (var index = 0; index < this.getScene().meshes.length; index++) {
  23294. var mesh = this.getScene().meshes[index];
  23295. if (mesh.parent === this) {
  23296. mesh.clone(mesh.name, result);
  23297. }
  23298. }
  23299. }
  23300. result.computeWorldMatrix(true);
  23301. return result;
  23302. };
  23303. /**
  23304. * Disposes the InstancedMesh.
  23305. * Returns nothing.
  23306. */
  23307. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  23308. // Remove from mesh
  23309. var index = this._sourceMesh.instances.indexOf(this);
  23310. this._sourceMesh.instances.splice(index, 1);
  23311. _super.prototype.dispose.call(this, doNotRecurse);
  23312. };
  23313. return InstancedMesh;
  23314. }(BABYLON.AbstractMesh));
  23315. BABYLON.InstancedMesh = InstancedMesh;
  23316. })(BABYLON || (BABYLON = {}));
  23317. //# sourceMappingURL=babylon.instancedMesh.js.map
  23318. var BABYLON;
  23319. (function (BABYLON) {
  23320. var _InstancesBatch = (function () {
  23321. function _InstancesBatch() {
  23322. this.mustReturn = false;
  23323. this.visibleInstances = new Array();
  23324. this.renderSelf = new Array();
  23325. }
  23326. return _InstancesBatch;
  23327. }());
  23328. BABYLON._InstancesBatch = _InstancesBatch;
  23329. var Mesh = (function (_super) {
  23330. __extends(Mesh, _super);
  23331. /**
  23332. * @constructor
  23333. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  23334. * @param {Scene} scene The scene to add this mesh to.
  23335. * @param {Node} parent The parent of this mesh, if it has one
  23336. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  23337. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  23338. * When false, achieved by calling a clone(), also passing False.
  23339. * This will make creation of children, recursive.
  23340. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  23341. */
  23342. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  23343. if (parent === void 0) { parent = null; }
  23344. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23345. var _this = _super.call(this, name, scene) || this;
  23346. // Events
  23347. /**
  23348. * An event triggered before rendering the mesh
  23349. * @type {BABYLON.Observable}
  23350. */
  23351. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23352. /**
  23353. * An event triggered after rendering the mesh
  23354. * @type {BABYLON.Observable}
  23355. */
  23356. _this.onAfterRenderObservable = new BABYLON.Observable();
  23357. /**
  23358. * An event triggered before drawing the mesh
  23359. * @type {BABYLON.Observable}
  23360. */
  23361. _this.onBeforeDrawObservable = new BABYLON.Observable();
  23362. // Members
  23363. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23364. _this.instances = new Array();
  23365. _this._LODLevels = new Array();
  23366. _this._visibleInstances = {};
  23367. _this._renderIdForInstances = new Array();
  23368. _this._batchCache = new _InstancesBatch();
  23369. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  23370. _this._sideOrientation = Mesh._DEFAULTSIDE;
  23371. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  23372. // Will be used to save a source mesh reference, If any
  23373. _this._source = null;
  23374. if (source) {
  23375. // Source mesh
  23376. _this._source = source;
  23377. // Geometry
  23378. if (source._geometry) {
  23379. source._geometry.applyToMesh(_this);
  23380. }
  23381. // Deep copy
  23382. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  23383. // Parent
  23384. _this.parent = source.parent;
  23385. // Pivot
  23386. _this.setPivotMatrix(source.getPivotMatrix());
  23387. _this.id = name + "." + source.id;
  23388. // Material
  23389. _this.material = source.material;
  23390. var index;
  23391. if (!doNotCloneChildren) {
  23392. // Children
  23393. for (index = 0; index < scene.meshes.length; index++) {
  23394. var mesh = scene.meshes[index];
  23395. if (mesh.parent === source) {
  23396. // doNotCloneChildren is always going to be False
  23397. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  23398. }
  23399. }
  23400. }
  23401. // Physics clone
  23402. var physicsEngine = _this.getScene().getPhysicsEngine();
  23403. if (clonePhysicsImpostor && physicsEngine) {
  23404. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  23405. if (impostor) {
  23406. _this.physicsImpostor = impostor.clone(_this);
  23407. }
  23408. }
  23409. // Particles
  23410. for (index = 0; index < scene.particleSystems.length; index++) {
  23411. var system = scene.particleSystems[index];
  23412. if (system.emitter === source) {
  23413. system.clone(system.name, _this);
  23414. }
  23415. }
  23416. _this.computeWorldMatrix(true);
  23417. }
  23418. // Parent
  23419. if (parent !== null) {
  23420. _this.parent = parent;
  23421. }
  23422. return _this;
  23423. }
  23424. Object.defineProperty(Mesh, "FRONTSIDE", {
  23425. /**
  23426. * Mesh side orientation : usually the external or front surface
  23427. */
  23428. get: function () {
  23429. return Mesh._FRONTSIDE;
  23430. },
  23431. enumerable: true,
  23432. configurable: true
  23433. });
  23434. Object.defineProperty(Mesh, "BACKSIDE", {
  23435. /**
  23436. * Mesh side orientation : usually the internal or back surface
  23437. */
  23438. get: function () {
  23439. return Mesh._BACKSIDE;
  23440. },
  23441. enumerable: true,
  23442. configurable: true
  23443. });
  23444. Object.defineProperty(Mesh, "DOUBLESIDE", {
  23445. /**
  23446. * Mesh side orientation : both internal and external or front and back surfaces
  23447. */
  23448. get: function () {
  23449. return Mesh._DOUBLESIDE;
  23450. },
  23451. enumerable: true,
  23452. configurable: true
  23453. });
  23454. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  23455. /**
  23456. * Mesh side orientation : by default, `FRONTSIDE`
  23457. */
  23458. get: function () {
  23459. return Mesh._DEFAULTSIDE;
  23460. },
  23461. enumerable: true,
  23462. configurable: true
  23463. });
  23464. Object.defineProperty(Mesh, "NO_CAP", {
  23465. /**
  23466. * Mesh cap setting : no cap
  23467. */
  23468. get: function () {
  23469. return Mesh._NO_CAP;
  23470. },
  23471. enumerable: true,
  23472. configurable: true
  23473. });
  23474. Object.defineProperty(Mesh, "CAP_START", {
  23475. /**
  23476. * Mesh cap setting : one cap at the beginning of the mesh
  23477. */
  23478. get: function () {
  23479. return Mesh._CAP_START;
  23480. },
  23481. enumerable: true,
  23482. configurable: true
  23483. });
  23484. Object.defineProperty(Mesh, "CAP_END", {
  23485. /**
  23486. * Mesh cap setting : one cap at the end of the mesh
  23487. */
  23488. get: function () {
  23489. return Mesh._CAP_END;
  23490. },
  23491. enumerable: true,
  23492. configurable: true
  23493. });
  23494. Object.defineProperty(Mesh, "CAP_ALL", {
  23495. /**
  23496. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  23497. */
  23498. get: function () {
  23499. return Mesh._CAP_ALL;
  23500. },
  23501. enumerable: true,
  23502. configurable: true
  23503. });
  23504. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  23505. set: function (callback) {
  23506. if (this._onBeforeDrawObserver) {
  23507. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  23508. }
  23509. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  23510. },
  23511. enumerable: true,
  23512. configurable: true
  23513. });
  23514. Object.defineProperty(Mesh.prototype, "source", {
  23515. get: function () {
  23516. return this._source;
  23517. },
  23518. enumerable: true,
  23519. configurable: true
  23520. });
  23521. // Methods
  23522. /**
  23523. * Returns the string "Mesh".
  23524. */
  23525. Mesh.prototype.getClassName = function () {
  23526. return "Mesh";
  23527. };
  23528. /**
  23529. * Returns a string.
  23530. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23531. */
  23532. Mesh.prototype.toString = function (fullDetails) {
  23533. var ret = _super.prototype.toString.call(this, fullDetails);
  23534. ret += ", n vertices: " + this.getTotalVertices();
  23535. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  23536. if (this.animations) {
  23537. for (var i = 0; i < this.animations.length; i++) {
  23538. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23539. }
  23540. }
  23541. if (fullDetails) {
  23542. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  23543. }
  23544. return ret;
  23545. };
  23546. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  23547. /**
  23548. * True if the mesh has some Levels Of Details (LOD).
  23549. * Returns a boolean.
  23550. */
  23551. get: function () {
  23552. return this._LODLevels.length > 0;
  23553. },
  23554. enumerable: true,
  23555. configurable: true
  23556. });
  23557. Mesh.prototype._sortLODLevels = function () {
  23558. this._LODLevels.sort(function (a, b) {
  23559. if (a.distance < b.distance) {
  23560. return 1;
  23561. }
  23562. if (a.distance > b.distance) {
  23563. return -1;
  23564. }
  23565. return 0;
  23566. });
  23567. };
  23568. /**
  23569. * Add a mesh as LOD level triggered at the given distance.
  23570. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23571. * @param {number} distance The distance from the center of the object to show this level
  23572. * @param {Mesh} mesh The mesh to be added as LOD level
  23573. * @return {Mesh} This mesh (for chaining)
  23574. */
  23575. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23576. if (mesh && mesh._masterMesh) {
  23577. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23578. return this;
  23579. }
  23580. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23581. this._LODLevels.push(level);
  23582. if (mesh) {
  23583. mesh._masterMesh = this;
  23584. }
  23585. this._sortLODLevels();
  23586. return this;
  23587. };
  23588. /**
  23589. * Returns the LOD level mesh at the passed distance or null if not found.
  23590. * It is related to the method `addLODLevel(distance, mesh)`.
  23591. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23592. * Returns an object Mesh or `null`.
  23593. */
  23594. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23595. for (var index = 0; index < this._LODLevels.length; index++) {
  23596. var level = this._LODLevels[index];
  23597. if (level.distance === distance) {
  23598. return level.mesh;
  23599. }
  23600. }
  23601. return null;
  23602. };
  23603. /**
  23604. * Remove a mesh from the LOD array
  23605. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23606. * @param {Mesh} mesh The mesh to be removed.
  23607. * @return {Mesh} This mesh (for chaining)
  23608. */
  23609. Mesh.prototype.removeLODLevel = function (mesh) {
  23610. for (var index = 0; index < this._LODLevels.length; index++) {
  23611. if (this._LODLevels[index].mesh === mesh) {
  23612. this._LODLevels.splice(index, 1);
  23613. if (mesh) {
  23614. mesh._masterMesh = null;
  23615. }
  23616. }
  23617. }
  23618. this._sortLODLevels();
  23619. return this;
  23620. };
  23621. /**
  23622. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23623. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23624. */
  23625. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23626. if (!this._LODLevels || this._LODLevels.length === 0) {
  23627. return this;
  23628. }
  23629. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  23630. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23631. if (this.onLODLevelSelection) {
  23632. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23633. }
  23634. return this;
  23635. }
  23636. for (var index = 0; index < this._LODLevels.length; index++) {
  23637. var level = this._LODLevels[index];
  23638. if (level.distance < distanceToCamera) {
  23639. if (level.mesh) {
  23640. level.mesh._preActivate();
  23641. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23642. }
  23643. if (this.onLODLevelSelection) {
  23644. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23645. }
  23646. return level.mesh;
  23647. }
  23648. }
  23649. if (this.onLODLevelSelection) {
  23650. this.onLODLevelSelection(distanceToCamera, this, this);
  23651. }
  23652. return this;
  23653. };
  23654. Object.defineProperty(Mesh.prototype, "geometry", {
  23655. /**
  23656. * Returns the mesh internal Geometry object.
  23657. */
  23658. get: function () {
  23659. return this._geometry;
  23660. },
  23661. enumerable: true,
  23662. configurable: true
  23663. });
  23664. /**
  23665. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23666. */
  23667. Mesh.prototype.getTotalVertices = function () {
  23668. if (!this._geometry) {
  23669. return 0;
  23670. }
  23671. return this._geometry.getTotalVertices();
  23672. };
  23673. /**
  23674. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23675. * 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.
  23676. * Returns null if the mesh has no geometry or no vertex buffer.
  23677. * Possible `kind` values :
  23678. * - BABYLON.VertexBuffer.PositionKind
  23679. * - BABYLON.VertexBuffer.UVKind
  23680. * - BABYLON.VertexBuffer.UV2Kind
  23681. * - BABYLON.VertexBuffer.UV3Kind
  23682. * - BABYLON.VertexBuffer.UV4Kind
  23683. * - BABYLON.VertexBuffer.UV5Kind
  23684. * - BABYLON.VertexBuffer.UV6Kind
  23685. * - BABYLON.VertexBuffer.ColorKind
  23686. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23687. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23688. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23689. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23690. */
  23691. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  23692. if (!this._geometry) {
  23693. return null;
  23694. }
  23695. return this._geometry.getVerticesData(kind, copyWhenShared);
  23696. };
  23697. /**
  23698. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  23699. * Returns `undefined` if the mesh has no geometry.
  23700. * Possible `kind` values :
  23701. * - BABYLON.VertexBuffer.PositionKind
  23702. * - BABYLON.VertexBuffer.UVKind
  23703. * - BABYLON.VertexBuffer.UV2Kind
  23704. * - BABYLON.VertexBuffer.UV3Kind
  23705. * - BABYLON.VertexBuffer.UV4Kind
  23706. * - BABYLON.VertexBuffer.UV5Kind
  23707. * - BABYLON.VertexBuffer.UV6Kind
  23708. * - BABYLON.VertexBuffer.ColorKind
  23709. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23710. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23711. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23712. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23713. */
  23714. Mesh.prototype.getVertexBuffer = function (kind) {
  23715. if (!this._geometry) {
  23716. return undefined;
  23717. }
  23718. return this._geometry.getVertexBuffer(kind);
  23719. };
  23720. /**
  23721. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  23722. * Possible `kind` values :
  23723. * - BABYLON.VertexBuffer.PositionKind
  23724. * - BABYLON.VertexBuffer.UVKind
  23725. * - BABYLON.VertexBuffer.UV2Kind
  23726. * - BABYLON.VertexBuffer.UV3Kind
  23727. * - BABYLON.VertexBuffer.UV4Kind
  23728. * - BABYLON.VertexBuffer.UV5Kind
  23729. * - BABYLON.VertexBuffer.UV6Kind
  23730. * - BABYLON.VertexBuffer.ColorKind
  23731. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23732. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23733. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23734. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23735. */
  23736. Mesh.prototype.isVerticesDataPresent = function (kind) {
  23737. if (!this._geometry) {
  23738. if (this._delayInfo) {
  23739. return this._delayInfo.indexOf(kind) !== -1;
  23740. }
  23741. return false;
  23742. }
  23743. return this._geometry.isVerticesDataPresent(kind);
  23744. };
  23745. /**
  23746. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  23747. * Possible `kind` values :
  23748. * - BABYLON.VertexBuffer.PositionKind
  23749. * - BABYLON.VertexBuffer.UVKind
  23750. * - BABYLON.VertexBuffer.UV2Kind
  23751. * - BABYLON.VertexBuffer.UV3Kind
  23752. * - BABYLON.VertexBuffer.UV4Kind
  23753. * - BABYLON.VertexBuffer.UV5Kind
  23754. * - BABYLON.VertexBuffer.UV6Kind
  23755. * - BABYLON.VertexBuffer.ColorKind
  23756. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23757. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23758. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23759. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23760. */
  23761. Mesh.prototype.getVerticesDataKinds = function () {
  23762. if (!this._geometry) {
  23763. var result = [];
  23764. if (this._delayInfo) {
  23765. this._delayInfo.forEach(function (kind, index, array) {
  23766. result.push(kind);
  23767. });
  23768. }
  23769. return result;
  23770. }
  23771. return this._geometry.getVerticesDataKinds();
  23772. };
  23773. /**
  23774. * Returns a positive integer : the total number of indices in this mesh geometry.
  23775. * Returns zero if the mesh has no geometry.
  23776. */
  23777. Mesh.prototype.getTotalIndices = function () {
  23778. if (!this._geometry) {
  23779. return 0;
  23780. }
  23781. return this._geometry.getTotalIndices();
  23782. };
  23783. /**
  23784. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  23785. * 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.
  23786. * Returns an empty array if the mesh has no geometry.
  23787. */
  23788. Mesh.prototype.getIndices = function (copyWhenShared) {
  23789. if (!this._geometry) {
  23790. return [];
  23791. }
  23792. return this._geometry.getIndices(copyWhenShared);
  23793. };
  23794. Object.defineProperty(Mesh.prototype, "isBlocked", {
  23795. get: function () {
  23796. return this._masterMesh !== null && this._masterMesh !== undefined;
  23797. },
  23798. enumerable: true,
  23799. configurable: true
  23800. });
  23801. /**
  23802. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  23803. */
  23804. Mesh.prototype.isReady = function () {
  23805. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23806. return false;
  23807. }
  23808. return _super.prototype.isReady.call(this);
  23809. };
  23810. /**
  23811. * Boolean : true if the mesh has been disposed.
  23812. */
  23813. Mesh.prototype.isDisposed = function () {
  23814. return this._isDisposed;
  23815. };
  23816. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  23817. get: function () {
  23818. return this._sideOrientation;
  23819. },
  23820. /**
  23821. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  23822. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  23823. */
  23824. set: function (sideO) {
  23825. this._sideOrientation = sideO;
  23826. },
  23827. enumerable: true,
  23828. configurable: true
  23829. });
  23830. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  23831. /**
  23832. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  23833. * This property is pertinent only for updatable parametric shapes.
  23834. */
  23835. get: function () {
  23836. return this._areNormalsFrozen;
  23837. },
  23838. enumerable: true,
  23839. configurable: true
  23840. });
  23841. /**
  23842. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23843. * It has no effect at all on other shapes.
  23844. * It prevents the mesh normals from being recomputed on next `positions` array update.
  23845. * Returns the Mesh.
  23846. */
  23847. Mesh.prototype.freezeNormals = function () {
  23848. this._areNormalsFrozen = true;
  23849. return this;
  23850. };
  23851. /**
  23852. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23853. * It has no effect at all on other shapes.
  23854. * It reactivates the mesh normals computation if it was previously frozen.
  23855. * Returns the Mesh.
  23856. */
  23857. Mesh.prototype.unfreezeNormals = function () {
  23858. this._areNormalsFrozen = false;
  23859. return this;
  23860. };
  23861. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23862. /**
  23863. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23864. */
  23865. set: function (count) {
  23866. this._overridenInstanceCount = count;
  23867. },
  23868. enumerable: true,
  23869. configurable: true
  23870. });
  23871. // Methods
  23872. Mesh.prototype._preActivate = function () {
  23873. var sceneRenderId = this.getScene().getRenderId();
  23874. if (this._preActivateId === sceneRenderId) {
  23875. return this;
  23876. }
  23877. this._preActivateId = sceneRenderId;
  23878. this._visibleInstances = null;
  23879. return this;
  23880. };
  23881. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23882. if (this._visibleInstances) {
  23883. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23884. }
  23885. return this;
  23886. };
  23887. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23888. if (!this._visibleInstances) {
  23889. this._visibleInstances = {};
  23890. this._visibleInstances.defaultRenderId = renderId;
  23891. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23892. }
  23893. if (!this._visibleInstances[renderId]) {
  23894. this._visibleInstances[renderId] = new Array();
  23895. }
  23896. this._visibleInstances[renderId].push(instance);
  23897. return this;
  23898. };
  23899. /**
  23900. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23901. * This means the mesh underlying bounding box and sphere are recomputed.
  23902. * Returns the Mesh.
  23903. */
  23904. Mesh.prototype.refreshBoundingInfo = function () {
  23905. if (this._boundingInfo.isLocked) {
  23906. return;
  23907. }
  23908. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23909. if (data) {
  23910. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23911. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23912. }
  23913. if (this.subMeshes) {
  23914. for (var index = 0; index < this.subMeshes.length; index++) {
  23915. this.subMeshes[index].refreshBoundingInfo();
  23916. }
  23917. }
  23918. this._updateBoundingInfo();
  23919. return this;
  23920. };
  23921. Mesh.prototype._createGlobalSubMesh = function () {
  23922. var totalVertices = this.getTotalVertices();
  23923. if (!totalVertices || !this.getIndices()) {
  23924. return null;
  23925. }
  23926. this.releaseSubMeshes();
  23927. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23928. };
  23929. Mesh.prototype.subdivide = function (count) {
  23930. if (count < 1) {
  23931. return;
  23932. }
  23933. var totalIndices = this.getTotalIndices();
  23934. var subdivisionSize = (totalIndices / count) | 0;
  23935. var offset = 0;
  23936. // Ensure that subdivisionSize is a multiple of 3
  23937. while (subdivisionSize % 3 !== 0) {
  23938. subdivisionSize++;
  23939. }
  23940. this.releaseSubMeshes();
  23941. for (var index = 0; index < count; index++) {
  23942. if (offset >= totalIndices) {
  23943. break;
  23944. }
  23945. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23946. offset += subdivisionSize;
  23947. }
  23948. this.synchronizeInstances();
  23949. };
  23950. /**
  23951. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23952. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23953. * The `data` are either a numeric array either a Float32Array.
  23954. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23955. * 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).
  23956. * Note that a new underlying VertexBuffer object is created each call.
  23957. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23958. *
  23959. * Possible `kind` values :
  23960. * - BABYLON.VertexBuffer.PositionKind
  23961. * - BABYLON.VertexBuffer.UVKind
  23962. * - BABYLON.VertexBuffer.UV2Kind
  23963. * - BABYLON.VertexBuffer.UV3Kind
  23964. * - BABYLON.VertexBuffer.UV4Kind
  23965. * - BABYLON.VertexBuffer.UV5Kind
  23966. * - BABYLON.VertexBuffer.UV6Kind
  23967. * - BABYLON.VertexBuffer.ColorKind
  23968. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23969. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23970. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23971. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23972. *
  23973. * Returns the Mesh.
  23974. */
  23975. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23976. if (!this._geometry) {
  23977. var vertexData = new BABYLON.VertexData();
  23978. vertexData.set(data, kind);
  23979. var scene = this.getScene();
  23980. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23981. }
  23982. else {
  23983. this._geometry.setVerticesData(kind, data, updatable, stride);
  23984. }
  23985. return this;
  23986. };
  23987. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23988. if (updatable === void 0) { updatable = true; }
  23989. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  23990. return;
  23991. }
  23992. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23993. };
  23994. /**
  23995. * Sets the mesh VertexBuffer.
  23996. * Returns the Mesh.
  23997. */
  23998. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23999. if (!this._geometry) {
  24000. var scene = this.getScene();
  24001. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  24002. }
  24003. this._geometry.setVerticesBuffer(buffer);
  24004. return this;
  24005. };
  24006. /**
  24007. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  24008. * If the mesh has no geometry, it is simply returned as it is.
  24009. * The `data` are either a numeric array either a Float32Array.
  24010. * No new underlying VertexBuffer object is created.
  24011. * 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.
  24012. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  24013. *
  24014. * Possible `kind` values :
  24015. * - BABYLON.VertexBuffer.PositionKind
  24016. * - BABYLON.VertexBuffer.UVKind
  24017. * - BABYLON.VertexBuffer.UV2Kind
  24018. * - BABYLON.VertexBuffer.UV3Kind
  24019. * - BABYLON.VertexBuffer.UV4Kind
  24020. * - BABYLON.VertexBuffer.UV5Kind
  24021. * - BABYLON.VertexBuffer.UV6Kind
  24022. * - BABYLON.VertexBuffer.ColorKind
  24023. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24024. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24025. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24026. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24027. *
  24028. * Returns the Mesh.
  24029. */
  24030. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  24031. if (!this._geometry) {
  24032. return;
  24033. }
  24034. if (!makeItUnique) {
  24035. this._geometry.updateVerticesData(kind, data, updateExtends);
  24036. }
  24037. else {
  24038. this.makeGeometryUnique();
  24039. this.updateVerticesData(kind, data, updateExtends, false);
  24040. }
  24041. return this;
  24042. };
  24043. /**
  24044. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  24045. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  24046. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  24047. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  24048. * Returns the Mesh.
  24049. */
  24050. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  24051. if (computeNormals === void 0) { computeNormals = true; }
  24052. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24053. positionFunction(positions);
  24054. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  24055. if (computeNormals) {
  24056. var indices = this.getIndices();
  24057. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24058. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  24059. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  24060. }
  24061. return this;
  24062. };
  24063. /**
  24064. * Creates a un-shared specific occurence of the geometry for the mesh.
  24065. * Returns the Mesh.
  24066. */
  24067. Mesh.prototype.makeGeometryUnique = function () {
  24068. if (!this._geometry) {
  24069. return;
  24070. }
  24071. var oldGeometry = this._geometry;
  24072. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  24073. oldGeometry.releaseForMesh(this, true);
  24074. geometry.applyToMesh(this);
  24075. return this;
  24076. };
  24077. /**
  24078. * Sets the mesh indices.
  24079. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  24080. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  24081. * This method creates a new index buffer each call.
  24082. * Returns the Mesh.
  24083. */
  24084. Mesh.prototype.setIndices = function (indices, totalVertices) {
  24085. if (!this._geometry) {
  24086. var vertexData = new BABYLON.VertexData();
  24087. vertexData.indices = indices;
  24088. var scene = this.getScene();
  24089. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  24090. }
  24091. else {
  24092. this._geometry.setIndices(indices, totalVertices);
  24093. }
  24094. return this;
  24095. };
  24096. /**
  24097. * Invert the geometry to move from a right handed system to a left handed one.
  24098. * Returns the Mesh.
  24099. */
  24100. Mesh.prototype.toLeftHanded = function () {
  24101. if (!this._geometry) {
  24102. return;
  24103. }
  24104. this._geometry.toLeftHanded();
  24105. return this;
  24106. };
  24107. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  24108. var engine = this.getScene().getEngine();
  24109. // Wireframe
  24110. var indexToBind;
  24111. if (this._unIndexed) {
  24112. indexToBind = null;
  24113. }
  24114. else {
  24115. switch (fillMode) {
  24116. case BABYLON.Material.PointFillMode:
  24117. indexToBind = null;
  24118. break;
  24119. case BABYLON.Material.WireFrameFillMode:
  24120. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  24121. break;
  24122. default:
  24123. case BABYLON.Material.TriangleFillMode:
  24124. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  24125. break;
  24126. }
  24127. }
  24128. // VBOs
  24129. this._geometry._bind(effect, indexToBind);
  24130. return this;
  24131. };
  24132. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  24133. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24134. return this;
  24135. }
  24136. this.onBeforeDrawObservable.notifyObservers(this);
  24137. var engine = this.getScene().getEngine();
  24138. // Draw order
  24139. switch (fillMode) {
  24140. case BABYLON.Material.PointFillMode:
  24141. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  24142. break;
  24143. case BABYLON.Material.WireFrameFillMode:
  24144. if (this._unIndexed) {
  24145. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  24146. }
  24147. else {
  24148. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  24149. }
  24150. break;
  24151. default:
  24152. if (this._unIndexed) {
  24153. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  24154. }
  24155. else {
  24156. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  24157. }
  24158. }
  24159. return this;
  24160. };
  24161. /**
  24162. * Registers for this mesh a javascript function called just before the rendering process.
  24163. * This function is passed the current mesh.
  24164. * Return the Mesh.
  24165. */
  24166. Mesh.prototype.registerBeforeRender = function (func) {
  24167. this.onBeforeRenderObservable.add(func);
  24168. return this;
  24169. };
  24170. /**
  24171. * Disposes a previously registered javascript function called before the rendering.
  24172. * This function is passed the current mesh.
  24173. * Returns the Mesh.
  24174. */
  24175. Mesh.prototype.unregisterBeforeRender = function (func) {
  24176. this.onBeforeRenderObservable.removeCallback(func);
  24177. return this;
  24178. };
  24179. /**
  24180. * Registers for this mesh a javascript function called just after the rendering is complete.
  24181. * This function is passed the current mesh.
  24182. * Returns the Mesh.
  24183. */
  24184. Mesh.prototype.registerAfterRender = function (func) {
  24185. this.onAfterRenderObservable.add(func);
  24186. return this;
  24187. };
  24188. /**
  24189. * Disposes a previously registered javascript function called after the rendering.
  24190. * This function is passed the current mesh.
  24191. * Return the Mesh.
  24192. */
  24193. Mesh.prototype.unregisterAfterRender = function (func) {
  24194. this.onAfterRenderObservable.removeCallback(func);
  24195. return this;
  24196. };
  24197. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  24198. var scene = this.getScene();
  24199. this._batchCache.mustReturn = false;
  24200. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  24201. this._batchCache.visibleInstances[subMeshId] = null;
  24202. if (this._visibleInstances) {
  24203. var currentRenderId = scene.getRenderId();
  24204. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  24205. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  24206. var selfRenderId = this._renderId;
  24207. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  24208. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  24209. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  24210. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  24211. }
  24212. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  24213. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  24214. this._batchCache.mustReturn = true;
  24215. return this._batchCache;
  24216. }
  24217. if (currentRenderId !== selfRenderId) {
  24218. this._batchCache.renderSelf[subMeshId] = false;
  24219. }
  24220. }
  24221. this._renderIdForInstances[subMeshId] = currentRenderId;
  24222. }
  24223. return this._batchCache;
  24224. };
  24225. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  24226. var visibleInstances = batch.visibleInstances[subMesh._id];
  24227. var matricesCount = visibleInstances.length + 1;
  24228. var bufferSize = matricesCount * 16 * 4;
  24229. var currentInstancesBufferSize = this._instancesBufferSize;
  24230. var instancesBuffer = this._instancesBuffer;
  24231. while (this._instancesBufferSize < bufferSize) {
  24232. this._instancesBufferSize *= 2;
  24233. }
  24234. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  24235. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  24236. }
  24237. var offset = 0;
  24238. var instancesCount = 0;
  24239. var world = this.getWorldMatrix();
  24240. if (batch.renderSelf[subMesh._id]) {
  24241. world.copyToArray(this._instancesData, offset);
  24242. offset += 16;
  24243. instancesCount++;
  24244. }
  24245. if (visibleInstances) {
  24246. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  24247. var instance = visibleInstances[instanceIndex];
  24248. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  24249. offset += 16;
  24250. instancesCount++;
  24251. }
  24252. }
  24253. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  24254. if (instancesBuffer) {
  24255. instancesBuffer.dispose();
  24256. }
  24257. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  24258. this._instancesBuffer = instancesBuffer;
  24259. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  24260. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  24261. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  24262. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  24263. }
  24264. else {
  24265. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  24266. }
  24267. this.geometry._bind(effect);
  24268. this._draw(subMesh, fillMode, instancesCount);
  24269. engine.unbindInstanceAttributes();
  24270. return this;
  24271. };
  24272. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  24273. var scene = this.getScene();
  24274. var engine = scene.getEngine();
  24275. if (hardwareInstancedRendering) {
  24276. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  24277. }
  24278. else {
  24279. if (batch.renderSelf[subMesh._id]) {
  24280. // Draw
  24281. if (onBeforeDraw) {
  24282. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  24283. }
  24284. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  24285. }
  24286. if (batch.visibleInstances[subMesh._id]) {
  24287. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  24288. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  24289. // World
  24290. var world = instance.getWorldMatrix();
  24291. if (onBeforeDraw) {
  24292. onBeforeDraw(true, world, effectiveMaterial);
  24293. }
  24294. // Draw
  24295. this._draw(subMesh, fillMode);
  24296. }
  24297. }
  24298. }
  24299. return this;
  24300. };
  24301. /**
  24302. * Triggers the draw call for the mesh.
  24303. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  24304. * Returns the Mesh.
  24305. */
  24306. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  24307. var scene = this.getScene();
  24308. // Managing instances
  24309. var batch = this._getInstancesRenderList(subMesh._id);
  24310. if (batch.mustReturn) {
  24311. return this;
  24312. }
  24313. // Checking geometry state
  24314. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24315. return this;
  24316. }
  24317. var callbackIndex;
  24318. this.onBeforeRenderObservable.notifyObservers(this);
  24319. var engine = scene.getEngine();
  24320. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24321. // Material
  24322. var effectiveMaterial = subMesh.getMaterial();
  24323. if (!effectiveMaterial) {
  24324. return this;
  24325. }
  24326. if (effectiveMaterial.storeEffectOnSubMeshes) {
  24327. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  24328. return this;
  24329. }
  24330. }
  24331. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  24332. return this;
  24333. }
  24334. // Outline - step 1
  24335. var savedDepthWrite = engine.getDepthWrite();
  24336. if (this.renderOutline) {
  24337. engine.setDepthWrite(false);
  24338. scene.getOutlineRenderer().render(subMesh, batch);
  24339. engine.setDepthWrite(savedDepthWrite);
  24340. }
  24341. var effect;
  24342. if (effectiveMaterial.storeEffectOnSubMeshes) {
  24343. effect = subMesh.effect;
  24344. }
  24345. else {
  24346. effect = effectiveMaterial.getEffect();
  24347. }
  24348. effectiveMaterial._preBind(effect);
  24349. // Bind
  24350. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  24351. this._bind(subMesh, effect, fillMode);
  24352. var world = this.getWorldMatrix();
  24353. if (effectiveMaterial.storeEffectOnSubMeshes) {
  24354. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  24355. }
  24356. else {
  24357. effectiveMaterial.bind(world, this);
  24358. }
  24359. // Alpha mode
  24360. if (enableAlphaMode) {
  24361. engine.setAlphaMode(effectiveMaterial.alphaMode);
  24362. }
  24363. // Draw
  24364. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  24365. // Unbind
  24366. effectiveMaterial.unbind();
  24367. // Outline - step 2
  24368. if (this.renderOutline && savedDepthWrite) {
  24369. engine.setDepthWrite(true);
  24370. engine.setColorWrite(false);
  24371. scene.getOutlineRenderer().render(subMesh, batch);
  24372. engine.setColorWrite(true);
  24373. }
  24374. // Overlay
  24375. if (this.renderOverlay) {
  24376. var currentMode = engine.getAlphaMode();
  24377. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24378. scene.getOutlineRenderer().render(subMesh, batch, true);
  24379. engine.setAlphaMode(currentMode);
  24380. }
  24381. this.onAfterRenderObservable.notifyObservers(this);
  24382. return this;
  24383. };
  24384. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  24385. if (isInstance) {
  24386. effectiveMaterial.bindOnlyWorldMatrix(world);
  24387. }
  24388. return this;
  24389. };
  24390. /**
  24391. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  24392. */
  24393. Mesh.prototype.getEmittedParticleSystems = function () {
  24394. var results = new Array();
  24395. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24396. var particleSystem = this.getScene().particleSystems[index];
  24397. if (particleSystem.emitter === this) {
  24398. results.push(particleSystem);
  24399. }
  24400. }
  24401. return results;
  24402. };
  24403. /**
  24404. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  24405. */
  24406. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  24407. var results = new Array();
  24408. var descendants = this.getDescendants();
  24409. descendants.push(this);
  24410. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24411. var particleSystem = this.getScene().particleSystems[index];
  24412. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  24413. results.push(particleSystem);
  24414. }
  24415. }
  24416. return results;
  24417. };
  24418. Mesh.prototype._checkDelayState = function () {
  24419. var scene = this.getScene();
  24420. if (this._geometry) {
  24421. this._geometry.load(scene);
  24422. }
  24423. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24424. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24425. this._queueLoad(this, scene);
  24426. }
  24427. return this;
  24428. };
  24429. Mesh.prototype._queueLoad = function (mesh, scene) {
  24430. var _this = this;
  24431. scene._addPendingData(mesh);
  24432. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  24433. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24434. if (data instanceof ArrayBuffer) {
  24435. _this._delayLoadingFunction(data, _this);
  24436. }
  24437. else {
  24438. _this._delayLoadingFunction(JSON.parse(data), _this);
  24439. }
  24440. _this.instances.forEach(function (instance) {
  24441. instance._syncSubMeshes();
  24442. });
  24443. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24444. scene._removePendingData(_this);
  24445. }, function () { }, scene.database, getBinaryData);
  24446. return this;
  24447. };
  24448. /**
  24449. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  24450. */
  24451. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  24452. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24453. return false;
  24454. }
  24455. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  24456. return false;
  24457. }
  24458. this._checkDelayState();
  24459. return true;
  24460. };
  24461. /**
  24462. * Sets the mesh material by the material or multiMaterial `id` property.
  24463. * The material `id` is a string identifying the material or the multiMaterial.
  24464. * This method returns the Mesh.
  24465. */
  24466. Mesh.prototype.setMaterialByID = function (id) {
  24467. var materials = this.getScene().materials;
  24468. var index;
  24469. for (index = 0; index < materials.length; index++) {
  24470. if (materials[index].id === id) {
  24471. this.material = materials[index];
  24472. return this;
  24473. }
  24474. }
  24475. // Multi
  24476. var multiMaterials = this.getScene().multiMaterials;
  24477. for (index = 0; index < multiMaterials.length; index++) {
  24478. if (multiMaterials[index].id === id) {
  24479. this.material = multiMaterials[index];
  24480. return this;
  24481. }
  24482. }
  24483. return this;
  24484. };
  24485. /**
  24486. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  24487. */
  24488. Mesh.prototype.getAnimatables = function () {
  24489. var results = [];
  24490. if (this.material) {
  24491. results.push(this.material);
  24492. }
  24493. if (this.skeleton) {
  24494. results.push(this.skeleton);
  24495. }
  24496. return results;
  24497. };
  24498. /**
  24499. * Modifies the mesh geometry according to the passed transformation matrix.
  24500. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  24501. * The mesh normals are modified accordingly the same transformation.
  24502. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24503. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24504. * Returns the Mesh.
  24505. */
  24506. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  24507. // Position
  24508. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24509. return this;
  24510. }
  24511. var submeshes = this.subMeshes.splice(0);
  24512. this._resetPointsArrayCache();
  24513. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24514. var temp = [];
  24515. var index;
  24516. for (index = 0; index < data.length; index += 3) {
  24517. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  24518. }
  24519. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  24520. // Normals
  24521. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24522. return this;
  24523. }
  24524. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24525. temp = [];
  24526. for (index = 0; index < data.length; index += 3) {
  24527. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  24528. }
  24529. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  24530. // flip faces?
  24531. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  24532. this.flipFaces();
  24533. }
  24534. // Restore submeshes
  24535. this.releaseSubMeshes();
  24536. this.subMeshes = submeshes;
  24537. return this;
  24538. };
  24539. /**
  24540. * Modifies the mesh geometry according to its own current World Matrix.
  24541. * The mesh World Matrix is then reset.
  24542. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  24543. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24544. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24545. * Returns the Mesh.
  24546. */
  24547. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  24548. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  24549. this.scaling.copyFromFloats(1, 1, 1);
  24550. this.position.copyFromFloats(0, 0, 0);
  24551. this.rotation.copyFromFloats(0, 0, 0);
  24552. //only if quaternion is already set
  24553. if (this.rotationQuaternion) {
  24554. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  24555. }
  24556. this._worldMatrix = BABYLON.Matrix.Identity();
  24557. return this;
  24558. };
  24559. // Cache
  24560. Mesh.prototype._resetPointsArrayCache = function () {
  24561. this._positions = null;
  24562. return this;
  24563. };
  24564. Mesh.prototype._generatePointsArray = function () {
  24565. if (this._positions)
  24566. return true;
  24567. this._positions = [];
  24568. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24569. if (!data) {
  24570. return false;
  24571. }
  24572. for (var index = 0; index < data.length; index += 3) {
  24573. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  24574. }
  24575. return true;
  24576. };
  24577. /**
  24578. * Returns a new Mesh object generated from the current mesh properties.
  24579. * This method must not get confused with createInstance().
  24580. * The parameter `name` is a string, the name given to the new mesh.
  24581. * The optional parameter `newParent` can be any Node object (default `null`).
  24582. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  24583. * 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.
  24584. */
  24585. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  24586. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24587. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  24588. };
  24589. /**
  24590. * Disposes the mesh.
  24591. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  24592. */
  24593. Mesh.prototype.dispose = function (doNotRecurse) {
  24594. var _this = this;
  24595. if (this._geometry) {
  24596. this._geometry.releaseForMesh(this, true);
  24597. }
  24598. // Sources
  24599. var meshes = this.getScene().meshes;
  24600. meshes.forEach(function (mesh) {
  24601. if (mesh._source && mesh._source === _this) {
  24602. mesh._source = null;
  24603. }
  24604. });
  24605. this._source = null;
  24606. // Instances
  24607. if (this._instancesBuffer) {
  24608. this._instancesBuffer.dispose();
  24609. this._instancesBuffer = null;
  24610. }
  24611. while (this.instances.length) {
  24612. this.instances[0].dispose();
  24613. }
  24614. // Highlight layers.
  24615. var highlightLayers = this.getScene().highlightLayers;
  24616. for (var i = 0; i < highlightLayers.length; i++) {
  24617. var highlightLayer = highlightLayers[i];
  24618. if (highlightLayer) {
  24619. highlightLayer.removeMesh(this);
  24620. highlightLayer.removeExcludedMesh(this);
  24621. }
  24622. }
  24623. _super.prototype.dispose.call(this, doNotRecurse);
  24624. };
  24625. /**
  24626. * Modifies the mesh geometry according to a displacement map.
  24627. * 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.
  24628. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24629. * This method returns nothing.
  24630. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  24631. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24632. * 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.
  24633. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24634. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24635. *
  24636. * Returns the Mesh.
  24637. */
  24638. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  24639. var _this = this;
  24640. var scene = this.getScene();
  24641. var onload = function (img) {
  24642. // Getting height map data
  24643. var canvas = document.createElement("canvas");
  24644. var context = canvas.getContext("2d");
  24645. var heightMapWidth = img.width;
  24646. var heightMapHeight = img.height;
  24647. canvas.width = heightMapWidth;
  24648. canvas.height = heightMapHeight;
  24649. context.drawImage(img, 0, 0);
  24650. // Create VertexData from map data
  24651. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  24652. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  24653. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  24654. //execute success callback, if set
  24655. if (onSuccess) {
  24656. onSuccess(_this);
  24657. }
  24658. };
  24659. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  24660. return this;
  24661. };
  24662. /**
  24663. * Modifies the mesh geometry according to a displacementMap buffer.
  24664. * 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.
  24665. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24666. * This method returns nothing.
  24667. * 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.
  24668. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  24669. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24670. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24671. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24672. *
  24673. * Returns the Mesh.
  24674. */
  24675. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  24676. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  24677. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  24678. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24679. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  24680. return this;
  24681. }
  24682. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24683. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24684. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24685. var position = BABYLON.Vector3.Zero();
  24686. var normal = BABYLON.Vector3.Zero();
  24687. var uv = BABYLON.Vector2.Zero();
  24688. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  24689. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  24690. for (var index = 0; index < positions.length; index += 3) {
  24691. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  24692. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  24693. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  24694. // Compute height
  24695. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  24696. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  24697. var pos = (u + v * heightMapWidth) * 4;
  24698. var r = buffer[pos] / 255.0;
  24699. var g = buffer[pos + 1] / 255.0;
  24700. var b = buffer[pos + 2] / 255.0;
  24701. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24702. normal.normalize();
  24703. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  24704. position = position.add(normal);
  24705. position.toArray(positions, index);
  24706. }
  24707. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  24708. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  24709. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24710. return this;
  24711. };
  24712. /**
  24713. * Modify the mesh to get a flat shading rendering.
  24714. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  24715. * This method returns the Mesh.
  24716. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  24717. */
  24718. Mesh.prototype.convertToFlatShadedMesh = function () {
  24719. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  24720. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24721. var kinds = this.getVerticesDataKinds();
  24722. var vbs = [];
  24723. var data = [];
  24724. var newdata = [];
  24725. var updatableNormals = false;
  24726. var kindIndex;
  24727. var kind;
  24728. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24729. kind = kinds[kindIndex];
  24730. var vertexBuffer = this.getVertexBuffer(kind);
  24731. if (kind === BABYLON.VertexBuffer.NormalKind) {
  24732. updatableNormals = vertexBuffer.isUpdatable();
  24733. kinds.splice(kindIndex, 1);
  24734. kindIndex--;
  24735. continue;
  24736. }
  24737. vbs[kind] = vertexBuffer;
  24738. data[kind] = vbs[kind].getData();
  24739. newdata[kind] = [];
  24740. }
  24741. // Save previous submeshes
  24742. var previousSubmeshes = this.subMeshes.slice(0);
  24743. var indices = this.getIndices();
  24744. var totalIndices = this.getTotalIndices();
  24745. // Generating unique vertices per face
  24746. var index;
  24747. for (index = 0; index < totalIndices; index++) {
  24748. var vertexIndex = indices[index];
  24749. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24750. kind = kinds[kindIndex];
  24751. var stride = vbs[kind].getStrideSize();
  24752. for (var offset = 0; offset < stride; offset++) {
  24753. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24754. }
  24755. }
  24756. }
  24757. // Updating faces & normal
  24758. var normals = [];
  24759. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24760. for (index = 0; index < totalIndices; index += 3) {
  24761. indices[index] = index;
  24762. indices[index + 1] = index + 1;
  24763. indices[index + 2] = index + 2;
  24764. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24765. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24766. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24767. var p1p2 = p1.subtract(p2);
  24768. var p3p2 = p3.subtract(p2);
  24769. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24770. // Store same normals for every vertex
  24771. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24772. normals.push(normal.x);
  24773. normals.push(normal.y);
  24774. normals.push(normal.z);
  24775. }
  24776. }
  24777. this.setIndices(indices);
  24778. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24779. // Updating vertex buffers
  24780. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24781. kind = kinds[kindIndex];
  24782. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24783. }
  24784. // Updating submeshes
  24785. this.releaseSubMeshes();
  24786. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24787. var previousOne = previousSubmeshes[submeshIndex];
  24788. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24789. }
  24790. this.synchronizeInstances();
  24791. return this;
  24792. };
  24793. /**
  24794. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24795. * In other words, more vertices, no more indices and a single bigger VBO.
  24796. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24797. * Returns the Mesh.
  24798. */
  24799. Mesh.prototype.convertToUnIndexedMesh = function () {
  24800. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24801. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24802. var kinds = this.getVerticesDataKinds();
  24803. var vbs = [];
  24804. var data = [];
  24805. var newdata = [];
  24806. var updatableNormals = false;
  24807. var kindIndex;
  24808. var kind;
  24809. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24810. kind = kinds[kindIndex];
  24811. var vertexBuffer = this.getVertexBuffer(kind);
  24812. vbs[kind] = vertexBuffer;
  24813. data[kind] = vbs[kind].getData();
  24814. newdata[kind] = [];
  24815. }
  24816. // Save previous submeshes
  24817. var previousSubmeshes = this.subMeshes.slice(0);
  24818. var indices = this.getIndices();
  24819. var totalIndices = this.getTotalIndices();
  24820. // Generating unique vertices per face
  24821. var index;
  24822. for (index = 0; index < totalIndices; index++) {
  24823. var vertexIndex = indices[index];
  24824. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24825. kind = kinds[kindIndex];
  24826. var stride = vbs[kind].getStrideSize();
  24827. for (var offset = 0; offset < stride; offset++) {
  24828. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24829. }
  24830. }
  24831. }
  24832. // Updating indices
  24833. for (index = 0; index < totalIndices; index += 3) {
  24834. indices[index] = index;
  24835. indices[index + 1] = index + 1;
  24836. indices[index + 2] = index + 2;
  24837. }
  24838. this.setIndices(indices);
  24839. // Updating vertex buffers
  24840. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24841. kind = kinds[kindIndex];
  24842. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24843. }
  24844. // Updating submeshes
  24845. this.releaseSubMeshes();
  24846. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24847. var previousOne = previousSubmeshes[submeshIndex];
  24848. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24849. }
  24850. this._unIndexed = true;
  24851. this.synchronizeInstances();
  24852. return this;
  24853. };
  24854. /**
  24855. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24856. * This method returns the Mesh.
  24857. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24858. */
  24859. Mesh.prototype.flipFaces = function (flipNormals) {
  24860. if (flipNormals === void 0) { flipNormals = false; }
  24861. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24862. var i;
  24863. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24864. for (i = 0; i < vertex_data.normals.length; i++) {
  24865. vertex_data.normals[i] *= -1;
  24866. }
  24867. }
  24868. var temp;
  24869. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24870. // reassign indices
  24871. temp = vertex_data.indices[i + 1];
  24872. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24873. vertex_data.indices[i + 2] = temp;
  24874. }
  24875. vertex_data.applyToMesh(this);
  24876. return this;
  24877. };
  24878. // Instances
  24879. /**
  24880. * Creates a new InstancedMesh object from the mesh model.
  24881. * An instance shares the same properties and the same material than its model.
  24882. * Only these properties of each instance can then be set individually :
  24883. * - position
  24884. * - rotation
  24885. * - rotationQuaternion
  24886. * - setPivotMatrix
  24887. * - scaling
  24888. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24889. * Warning : this method is not supported for Line mesh and LineSystem
  24890. */
  24891. Mesh.prototype.createInstance = function (name) {
  24892. return new BABYLON.InstancedMesh(name, this);
  24893. };
  24894. /**
  24895. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24896. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24897. * This method returns the Mesh.
  24898. */
  24899. Mesh.prototype.synchronizeInstances = function () {
  24900. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24901. var instance = this.instances[instanceIndex];
  24902. instance._syncSubMeshes();
  24903. }
  24904. return this;
  24905. };
  24906. /**
  24907. * Simplify the mesh according to the given array of settings.
  24908. * Function will return immediately and will simplify async. It returns the Mesh.
  24909. * @param settings a collection of simplification settings.
  24910. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24911. * @param type the type of simplification to run.
  24912. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24913. */
  24914. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24915. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24916. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24917. this.getScene().simplificationQueue.addTask({
  24918. settings: settings,
  24919. parallelProcessing: parallelProcessing,
  24920. mesh: this,
  24921. simplificationType: simplificationType,
  24922. successCallback: successCallback
  24923. });
  24924. return this;
  24925. };
  24926. /**
  24927. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24928. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24929. * This should be used together with the simplification to avoid disappearing triangles.
  24930. * Returns the Mesh.
  24931. * @param successCallback an optional success callback to be called after the optimization finished.
  24932. */
  24933. Mesh.prototype.optimizeIndices = function (successCallback) {
  24934. var _this = this;
  24935. var indices = this.getIndices();
  24936. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24937. var vectorPositions = [];
  24938. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24939. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24940. }
  24941. var dupes = [];
  24942. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24943. var realPos = vectorPositions.length - 1 - iteration;
  24944. var testedPosition = vectorPositions[realPos];
  24945. for (var j = 0; j < realPos; ++j) {
  24946. var againstPosition = vectorPositions[j];
  24947. if (testedPosition.equals(againstPosition)) {
  24948. dupes[realPos] = j;
  24949. break;
  24950. }
  24951. }
  24952. }, function () {
  24953. for (var i = 0; i < indices.length; ++i) {
  24954. indices[i] = dupes[indices[i]] || indices[i];
  24955. }
  24956. //indices are now reordered
  24957. var originalSubMeshes = _this.subMeshes.slice(0);
  24958. _this.setIndices(indices);
  24959. _this.subMeshes = originalSubMeshes;
  24960. if (successCallback) {
  24961. successCallback(_this);
  24962. }
  24963. });
  24964. return this;
  24965. };
  24966. Mesh.prototype.serialize = function (serializationObject) {
  24967. serializationObject.name = this.name;
  24968. serializationObject.id = this.id;
  24969. serializationObject.type = this.getClassName();
  24970. if (BABYLON.Tags.HasTags(this)) {
  24971. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24972. }
  24973. serializationObject.position = this.position.asArray();
  24974. if (this.rotationQuaternion) {
  24975. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24976. }
  24977. else if (this.rotation) {
  24978. serializationObject.rotation = this.rotation.asArray();
  24979. }
  24980. serializationObject.scaling = this.scaling.asArray();
  24981. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24982. serializationObject.isEnabled = this.isEnabled();
  24983. serializationObject.isVisible = this.isVisible;
  24984. serializationObject.infiniteDistance = this.infiniteDistance;
  24985. serializationObject.pickable = this.isPickable;
  24986. serializationObject.receiveShadows = this.receiveShadows;
  24987. serializationObject.billboardMode = this.billboardMode;
  24988. serializationObject.visibility = this.visibility;
  24989. serializationObject.checkCollisions = this.checkCollisions;
  24990. serializationObject.isBlocker = this.isBlocker;
  24991. // Parent
  24992. if (this.parent) {
  24993. serializationObject.parentId = this.parent.id;
  24994. }
  24995. // Geometry
  24996. var geometry = this._geometry;
  24997. if (geometry) {
  24998. var geometryId = geometry.id;
  24999. serializationObject.geometryId = geometryId;
  25000. // SubMeshes
  25001. serializationObject.subMeshes = [];
  25002. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  25003. var subMesh = this.subMeshes[subIndex];
  25004. serializationObject.subMeshes.push({
  25005. materialIndex: subMesh.materialIndex,
  25006. verticesStart: subMesh.verticesStart,
  25007. verticesCount: subMesh.verticesCount,
  25008. indexStart: subMesh.indexStart,
  25009. indexCount: subMesh.indexCount
  25010. });
  25011. }
  25012. }
  25013. // Material
  25014. if (this.material) {
  25015. serializationObject.materialId = this.material.id;
  25016. }
  25017. else {
  25018. this.material = null;
  25019. }
  25020. // Skeleton
  25021. if (this.skeleton) {
  25022. serializationObject.skeletonId = this.skeleton.id;
  25023. }
  25024. // Physics
  25025. //TODO implement correct serialization for physics impostors.
  25026. if (this.getPhysicsImpostor()) {
  25027. var impostor = this.getPhysicsImpostor();
  25028. serializationObject.physicsMass = impostor.getParam("mass");
  25029. serializationObject.physicsFriction = impostor.getParam("friction");
  25030. serializationObject.physicsRestitution = impostor.getParam("mass");
  25031. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  25032. }
  25033. // Metadata
  25034. if (this.metadata) {
  25035. serializationObject.metadata = this.metadata;
  25036. }
  25037. // Instances
  25038. serializationObject.instances = [];
  25039. for (var index = 0; index < this.instances.length; index++) {
  25040. var instance = this.instances[index];
  25041. var serializationInstance = {
  25042. name: instance.name,
  25043. position: instance.position.asArray(),
  25044. scaling: instance.scaling.asArray()
  25045. };
  25046. if (instance.rotationQuaternion) {
  25047. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  25048. }
  25049. else if (instance.rotation) {
  25050. serializationInstance.rotation = instance.rotation.asArray();
  25051. }
  25052. serializationObject.instances.push(serializationInstance);
  25053. // Animations
  25054. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  25055. serializationInstance.ranges = instance.serializeAnimationRanges();
  25056. }
  25057. // Animations
  25058. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25059. serializationObject.ranges = this.serializeAnimationRanges();
  25060. // Layer mask
  25061. serializationObject.layerMask = this.layerMask;
  25062. // Alpha
  25063. serializationObject.alphaIndex = this.alphaIndex;
  25064. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  25065. // Overlay
  25066. serializationObject.overlayAlpha = this.overlayAlpha;
  25067. serializationObject.overlayColor = this.overlayColor.asArray();
  25068. serializationObject.renderOverlay = this.renderOverlay;
  25069. // Fog
  25070. serializationObject.applyFog = this.applyFog;
  25071. // Action Manager
  25072. if (this.actionManager) {
  25073. serializationObject.actions = this.actionManager.serialize(this.name);
  25074. }
  25075. };
  25076. // Statics
  25077. /**
  25078. * Returns a new Mesh object what is a deep copy of the passed mesh.
  25079. * The parameter `parsedMesh` is the mesh to be copied.
  25080. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  25081. */
  25082. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  25083. var mesh;
  25084. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  25085. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  25086. }
  25087. else {
  25088. mesh = new Mesh(parsedMesh.name, scene);
  25089. }
  25090. mesh.id = parsedMesh.id;
  25091. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  25092. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  25093. if (parsedMesh.metadata !== undefined) {
  25094. mesh.metadata = parsedMesh.metadata;
  25095. }
  25096. if (parsedMesh.rotationQuaternion) {
  25097. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  25098. }
  25099. else if (parsedMesh.rotation) {
  25100. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  25101. }
  25102. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  25103. if (parsedMesh.localMatrix) {
  25104. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  25105. }
  25106. else if (parsedMesh.pivotMatrix) {
  25107. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  25108. }
  25109. mesh.setEnabled(parsedMesh.isEnabled);
  25110. mesh.isVisible = parsedMesh.isVisible;
  25111. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  25112. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  25113. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  25114. if (parsedMesh.applyFog !== undefined) {
  25115. mesh.applyFog = parsedMesh.applyFog;
  25116. }
  25117. if (parsedMesh.pickable !== undefined) {
  25118. mesh.isPickable = parsedMesh.pickable;
  25119. }
  25120. if (parsedMesh.alphaIndex !== undefined) {
  25121. mesh.alphaIndex = parsedMesh.alphaIndex;
  25122. }
  25123. mesh.receiveShadows = parsedMesh.receiveShadows;
  25124. mesh.billboardMode = parsedMesh.billboardMode;
  25125. if (parsedMesh.visibility !== undefined) {
  25126. mesh.visibility = parsedMesh.visibility;
  25127. }
  25128. mesh.checkCollisions = parsedMesh.checkCollisions;
  25129. if (parsedMesh.isBlocker !== undefined) {
  25130. mesh.isBlocker = parsedMesh.isBlocker;
  25131. }
  25132. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  25133. // freezeWorldMatrix
  25134. if (parsedMesh.freezeWorldMatrix) {
  25135. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  25136. }
  25137. // Parent
  25138. if (parsedMesh.parentId) {
  25139. mesh._waitingParentId = parsedMesh.parentId;
  25140. }
  25141. // Actions
  25142. if (parsedMesh.actions !== undefined) {
  25143. mesh._waitingActions = parsedMesh.actions;
  25144. }
  25145. // Overlay
  25146. if (parsedMesh.overlayAlpha !== undefined) {
  25147. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  25148. }
  25149. if (parsedMesh.overlayColor !== undefined) {
  25150. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  25151. }
  25152. if (parsedMesh.renderOverlay !== undefined) {
  25153. mesh.renderOverlay = parsedMesh.renderOverlay;
  25154. }
  25155. // Geometry
  25156. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  25157. if (parsedMesh.delayLoadingFile) {
  25158. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25159. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  25160. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  25161. if (parsedMesh._binaryInfo) {
  25162. mesh._binaryInfo = parsedMesh._binaryInfo;
  25163. }
  25164. mesh._delayInfo = [];
  25165. if (parsedMesh.hasUVs) {
  25166. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  25167. }
  25168. if (parsedMesh.hasUVs2) {
  25169. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  25170. }
  25171. if (parsedMesh.hasUVs3) {
  25172. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  25173. }
  25174. if (parsedMesh.hasUVs4) {
  25175. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  25176. }
  25177. if (parsedMesh.hasUVs5) {
  25178. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  25179. }
  25180. if (parsedMesh.hasUVs6) {
  25181. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  25182. }
  25183. if (parsedMesh.hasColors) {
  25184. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  25185. }
  25186. if (parsedMesh.hasMatricesIndices) {
  25187. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25188. }
  25189. if (parsedMesh.hasMatricesWeights) {
  25190. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25191. }
  25192. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  25193. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  25194. mesh._checkDelayState();
  25195. }
  25196. }
  25197. else {
  25198. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  25199. }
  25200. // Material
  25201. if (parsedMesh.materialId) {
  25202. mesh.setMaterialByID(parsedMesh.materialId);
  25203. }
  25204. else {
  25205. mesh.material = null;
  25206. }
  25207. // Skeleton
  25208. if (parsedMesh.skeletonId > -1) {
  25209. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  25210. if (parsedMesh.numBoneInfluencers) {
  25211. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  25212. }
  25213. }
  25214. // Animations
  25215. if (parsedMesh.animations) {
  25216. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25217. var parsedAnimation = parsedMesh.animations[animationIndex];
  25218. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25219. }
  25220. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  25221. }
  25222. if (parsedMesh.autoAnimate) {
  25223. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  25224. }
  25225. // Layer Mask
  25226. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  25227. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  25228. }
  25229. else {
  25230. mesh.layerMask = 0x0FFFFFFF;
  25231. }
  25232. // Physics
  25233. if (parsedMesh.physicsImpostor) {
  25234. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  25235. mass: parsedMesh.physicsMass,
  25236. friction: parsedMesh.physicsFriction,
  25237. restitution: parsedMesh.physicsRestitution
  25238. }, scene);
  25239. }
  25240. // Instances
  25241. if (parsedMesh.instances) {
  25242. for (var index = 0; index < parsedMesh.instances.length; index++) {
  25243. var parsedInstance = parsedMesh.instances[index];
  25244. var instance = mesh.createInstance(parsedInstance.name);
  25245. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  25246. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  25247. if (parsedInstance.parentId) {
  25248. instance._waitingParentId = parsedInstance.parentId;
  25249. }
  25250. if (parsedInstance.rotationQuaternion) {
  25251. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  25252. }
  25253. else if (parsedInstance.rotation) {
  25254. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  25255. }
  25256. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  25257. instance.checkCollisions = mesh.checkCollisions;
  25258. if (parsedMesh.animations) {
  25259. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25260. parsedAnimation = parsedMesh.animations[animationIndex];
  25261. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25262. }
  25263. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  25264. }
  25265. }
  25266. }
  25267. return mesh;
  25268. };
  25269. /**
  25270. * Creates a ribbon mesh.
  25271. * Please consider using the same method from the MeshBuilder class instead.
  25272. * 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.
  25273. *
  25274. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25275. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25276. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25277. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25278. * 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.
  25279. * 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.
  25280. * 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
  25281. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25282. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25284. */
  25285. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  25286. return BABYLON.MeshBuilder.CreateRibbon(name, {
  25287. pathArray: pathArray,
  25288. closeArray: closeArray,
  25289. closePath: closePath,
  25290. offset: offset,
  25291. updatable: updatable,
  25292. sideOrientation: sideOrientation,
  25293. instance: instance
  25294. }, scene);
  25295. };
  25296. /**
  25297. * Creates a plane polygonal mesh. By default, this is a disc.
  25298. * Please consider using the same method from the MeshBuilder class instead.
  25299. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25300. * 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.
  25301. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25302. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25304. */
  25305. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  25306. var options = {
  25307. radius: radius,
  25308. tessellation: tessellation,
  25309. sideOrientation: sideOrientation,
  25310. updatable: updatable
  25311. };
  25312. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  25313. };
  25314. /**
  25315. * Creates a box mesh.
  25316. * Please consider using the same method from the MeshBuilder class instead.
  25317. * The parameter `size` sets the size (float) of each box side (default 1).
  25318. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25319. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25320. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25321. */
  25322. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  25323. var options = {
  25324. size: size,
  25325. sideOrientation: sideOrientation,
  25326. updatable: updatable
  25327. };
  25328. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  25329. };
  25330. /**
  25331. * Creates a sphere mesh.
  25332. * Please consider using the same method from the MeshBuilder class instead.
  25333. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25334. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25335. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25336. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25337. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25338. */
  25339. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  25340. var options = {
  25341. segments: segments,
  25342. diameterX: diameter,
  25343. diameterY: diameter,
  25344. diameterZ: diameter,
  25345. sideOrientation: sideOrientation,
  25346. updatable: updatable
  25347. };
  25348. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  25349. };
  25350. /**
  25351. * Creates a cylinder or a cone mesh.
  25352. * Please consider using the same method from the MeshBuilder class instead.
  25353. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25354. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25355. * 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.
  25356. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25357. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25358. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25359. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25360. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25361. */
  25362. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  25363. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  25364. if (scene !== undefined) {
  25365. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  25366. updatable = scene;
  25367. }
  25368. scene = subdivisions;
  25369. subdivisions = 1;
  25370. }
  25371. var options = {
  25372. height: height,
  25373. diameterTop: diameterTop,
  25374. diameterBottom: diameterBottom,
  25375. tessellation: tessellation,
  25376. subdivisions: subdivisions,
  25377. sideOrientation: sideOrientation,
  25378. updatable: updatable
  25379. };
  25380. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  25381. };
  25382. // Torus (Code from SharpDX.org)
  25383. /**
  25384. * Creates a torus mesh.
  25385. * Please consider using the same method from the MeshBuilder class instead.
  25386. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25387. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25388. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25389. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25390. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25391. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25392. */
  25393. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  25394. var options = {
  25395. diameter: diameter,
  25396. thickness: thickness,
  25397. tessellation: tessellation,
  25398. sideOrientation: sideOrientation,
  25399. updatable: updatable
  25400. };
  25401. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  25402. };
  25403. /**
  25404. * Creates a torus knot mesh.
  25405. * Please consider using the same method from the MeshBuilder class instead.
  25406. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25407. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25408. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25409. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25410. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25411. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25412. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25413. */
  25414. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  25415. var options = {
  25416. radius: radius,
  25417. tube: tube,
  25418. radialSegments: radialSegments,
  25419. tubularSegments: tubularSegments,
  25420. p: p,
  25421. q: q,
  25422. sideOrientation: sideOrientation,
  25423. updatable: updatable
  25424. };
  25425. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  25426. };
  25427. /**
  25428. * Creates a line mesh.
  25429. * Please consider using the same method from the MeshBuilder class instead.
  25430. * 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.
  25431. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25432. * The parameter `points` is an array successive Vector3.
  25433. * 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
  25434. * When updating an instance, remember that only point positions can change, not the number of points.
  25435. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25436. */
  25437. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  25438. var options = {
  25439. points: points,
  25440. updatable: updatable,
  25441. instance: instance
  25442. };
  25443. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  25444. };
  25445. /**
  25446. * Creates a dashed line mesh.
  25447. * Please consider using the same method from the MeshBuilder class instead.
  25448. * 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.
  25449. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25450. * The parameter `points` is an array successive Vector3.
  25451. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  25452. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  25453. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  25454. * 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
  25455. * When updating an instance, remember that only point positions can change, not the number of points.
  25456. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25457. */
  25458. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  25459. var options = {
  25460. points: points,
  25461. dashSize: dashSize,
  25462. gapSize: gapSize,
  25463. dashNb: dashNb,
  25464. updatable: updatable,
  25465. instance: instance
  25466. };
  25467. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  25468. };
  25469. /**
  25470. * Creates an extruded shape mesh.
  25471. * 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.
  25472. * Please consider using the same method from the MeshBuilder class instead.
  25473. *
  25474. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25475. * 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
  25476. * extruded along the Z axis.
  25477. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25478. * 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.
  25479. * The parameter `scale` (float, default 1) is the value to scale the shape.
  25480. * 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
  25481. * 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
  25482. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25483. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25484. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25485. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25486. */
  25487. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  25488. var options = {
  25489. shape: shape,
  25490. path: path,
  25491. scale: scale,
  25492. rotation: rotation,
  25493. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25494. sideOrientation: sideOrientation,
  25495. instance: instance,
  25496. updatable: updatable
  25497. };
  25498. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  25499. };
  25500. /**
  25501. * Creates an custom extruded shape mesh.
  25502. * 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.
  25503. * Please consider using the same method from the MeshBuilder class instead.
  25504. *
  25505. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25506. * 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
  25507. * extruded along the Z axis.
  25508. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25509. * 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
  25510. * and the distance of this point from the begining of the path :
  25511. * ```javascript
  25512. * var rotationFunction = function(i, distance) {
  25513. * // do things
  25514. * return rotationValue; }
  25515. * ```
  25516. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  25517. * 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
  25518. * and the distance of this point from the begining of the path :
  25519. * ```javascript
  25520. * var scaleFunction = function(i, distance) {
  25521. * // do things
  25522. * return scaleValue;}
  25523. * ```
  25524. * It must returns a float value that will be the scale value applied to the shape on each path point.
  25525. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  25526. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  25527. * 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
  25528. * 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
  25529. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25530. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25531. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25532. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25533. */
  25534. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  25535. var options = {
  25536. shape: shape,
  25537. path: path,
  25538. scaleFunction: scaleFunction,
  25539. rotationFunction: rotationFunction,
  25540. ribbonCloseArray: ribbonCloseArray,
  25541. ribbonClosePath: ribbonClosePath,
  25542. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25543. sideOrientation: sideOrientation,
  25544. instance: instance,
  25545. updatable: updatable
  25546. };
  25547. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  25548. };
  25549. /**
  25550. * Creates lathe mesh.
  25551. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25552. * Please consider using the same method from the MeshBuilder class instead.
  25553. * 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
  25554. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25555. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25556. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25557. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25558. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25559. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25560. */
  25561. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  25562. var options = {
  25563. shape: shape,
  25564. radius: radius,
  25565. tessellation: tessellation,
  25566. sideOrientation: sideOrientation,
  25567. updatable: updatable
  25568. };
  25569. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  25570. };
  25571. /**
  25572. * Creates a plane mesh.
  25573. * Please consider using the same method from the MeshBuilder class instead.
  25574. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25575. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25576. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25577. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25578. */
  25579. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  25580. var options = {
  25581. size: size,
  25582. width: size,
  25583. height: size,
  25584. sideOrientation: sideOrientation,
  25585. updatable: updatable
  25586. };
  25587. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  25588. };
  25589. /**
  25590. * Creates a ground mesh.
  25591. * Please consider using the same method from the MeshBuilder class instead.
  25592. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25593. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25594. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25595. */
  25596. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  25597. var options = {
  25598. width: width,
  25599. height: height,
  25600. subdivisions: subdivisions,
  25601. updatable: updatable
  25602. };
  25603. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  25604. };
  25605. /**
  25606. * Creates a tiled ground mesh.
  25607. * Please consider using the same method from the MeshBuilder class instead.
  25608. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25609. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25610. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25611. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25612. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25613. * numbers of subdivisions on the ground width and height of each tile.
  25614. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25615. */
  25616. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  25617. var options = {
  25618. xmin: xmin,
  25619. zmin: zmin,
  25620. xmax: xmax,
  25621. zmax: zmax,
  25622. subdivisions: subdivisions,
  25623. precision: precision,
  25624. updatable: updatable
  25625. };
  25626. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  25627. };
  25628. /**
  25629. * Creates a ground mesh from a height map.
  25630. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25631. * Please consider using the same method from the MeshBuilder class instead.
  25632. * The parameter `url` sets the URL of the height map image resource.
  25633. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25634. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25635. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25636. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25637. * 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).
  25638. * This function is passed the newly built mesh :
  25639. * ```javascript
  25640. * function(mesh) { // do things
  25641. * return; }
  25642. * ```
  25643. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25644. */
  25645. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  25646. var options = {
  25647. width: width,
  25648. height: height,
  25649. subdivisions: subdivisions,
  25650. minHeight: minHeight,
  25651. maxHeight: maxHeight,
  25652. updatable: updatable,
  25653. onReady: onReady
  25654. };
  25655. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25656. };
  25657. /**
  25658. * Creates a tube mesh.
  25659. * 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.
  25660. * Please consider using the same method from the MeshBuilder class instead.
  25661. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25662. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25663. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25664. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25665. * 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.
  25666. * It must return a radius value (positive float) :
  25667. * ```javascript
  25668. * var radiusFunction = function(i, distance) {
  25669. * // do things
  25670. * return radius; }
  25671. * ```
  25672. * 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
  25673. * 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
  25674. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25675. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25676. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25677. */
  25678. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25679. var options = {
  25680. path: path,
  25681. radius: radius,
  25682. tessellation: tessellation,
  25683. radiusFunction: radiusFunction,
  25684. arc: 1,
  25685. cap: cap,
  25686. updatable: updatable,
  25687. sideOrientation: sideOrientation,
  25688. instance: instance
  25689. };
  25690. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25691. };
  25692. /**
  25693. * Creates a polyhedron mesh.
  25694. * Please consider using the same method from the MeshBuilder class instead.
  25695. * 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
  25696. * to choose the wanted type.
  25697. * The parameter `size` (positive float, default 1) sets the polygon size.
  25698. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25699. * 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`.
  25700. * 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
  25701. * 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)`).
  25702. * 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
  25703. * 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.
  25704. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25705. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25706. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25707. */
  25708. Mesh.CreatePolyhedron = function (name, options, scene) {
  25709. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25710. };
  25711. /**
  25712. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25713. * Please consider using the same method from the MeshBuilder class instead.
  25714. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25715. * 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`).
  25716. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25717. * 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.
  25718. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25719. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25720. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25721. */
  25722. Mesh.CreateIcoSphere = function (name, options, scene) {
  25723. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25724. };
  25725. /**
  25726. * Creates a decal mesh.
  25727. * Please consider using the same method from the MeshBuilder class instead.
  25728. * 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.
  25729. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25730. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25731. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25732. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25733. */
  25734. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25735. var options = {
  25736. position: position,
  25737. normal: normal,
  25738. size: size,
  25739. angle: angle
  25740. };
  25741. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25742. };
  25743. // Skeletons
  25744. /**
  25745. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25746. */
  25747. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25748. var source;
  25749. if (!this._sourcePositions) {
  25750. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25751. this._sourcePositions = new Float32Array(source);
  25752. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  25753. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25754. }
  25755. }
  25756. return this._sourcePositions;
  25757. };
  25758. /**
  25759. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25760. */
  25761. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25762. var source;
  25763. if (!this._sourceNormals) {
  25764. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25765. this._sourceNormals = new Float32Array(source);
  25766. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  25767. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25768. }
  25769. }
  25770. return this._sourceNormals;
  25771. };
  25772. /**
  25773. * Updates the vertex buffer by applying transformation from the bones.
  25774. * Returns the Mesh.
  25775. *
  25776. * @param {skeleton} skeleton to apply
  25777. */
  25778. Mesh.prototype.applySkeleton = function (skeleton) {
  25779. if (!this.geometry) {
  25780. return this;
  25781. }
  25782. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25783. return this;
  25784. }
  25785. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25786. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25787. return this;
  25788. }
  25789. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25790. return this;
  25791. }
  25792. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25793. return this;
  25794. }
  25795. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25796. return this;
  25797. }
  25798. if (!this._sourcePositions) {
  25799. var submeshes = this.subMeshes.slice();
  25800. this.setPositionsForCPUSkinning();
  25801. this.subMeshes = submeshes;
  25802. }
  25803. if (!this._sourceNormals) {
  25804. this.setNormalsForCPUSkinning();
  25805. }
  25806. // positionsData checks for not being Float32Array will only pass at most once
  25807. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25808. if (!(positionsData instanceof Float32Array)) {
  25809. positionsData = new Float32Array(positionsData);
  25810. }
  25811. // normalsData checks for not being Float32Array will only pass at most once
  25812. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25813. if (!(normalsData instanceof Float32Array)) {
  25814. normalsData = new Float32Array(normalsData);
  25815. }
  25816. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25817. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25818. var needExtras = this.numBoneInfluencers > 4;
  25819. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25820. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25821. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25822. var tempVector3 = BABYLON.Vector3.Zero();
  25823. var finalMatrix = new BABYLON.Matrix();
  25824. var tempMatrix = new BABYLON.Matrix();
  25825. var matWeightIdx = 0;
  25826. var inf;
  25827. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25828. var weight;
  25829. for (inf = 0; inf < 4; inf++) {
  25830. weight = matricesWeightsData[matWeightIdx + inf];
  25831. if (weight > 0) {
  25832. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25833. finalMatrix.addToSelf(tempMatrix);
  25834. }
  25835. else
  25836. break;
  25837. }
  25838. if (needExtras) {
  25839. for (inf = 0; inf < 4; inf++) {
  25840. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25841. if (weight > 0) {
  25842. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25843. finalMatrix.addToSelf(tempMatrix);
  25844. }
  25845. else
  25846. break;
  25847. }
  25848. }
  25849. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25850. tempVector3.toArray(positionsData, index);
  25851. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25852. tempVector3.toArray(normalsData, index);
  25853. finalMatrix.reset();
  25854. }
  25855. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25856. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25857. return this;
  25858. };
  25859. // Tools
  25860. /**
  25861. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25862. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25863. */
  25864. Mesh.MinMax = function (meshes) {
  25865. var minVector = null;
  25866. var maxVector = null;
  25867. meshes.forEach(function (mesh, index, array) {
  25868. var boundingBox = mesh.getBoundingInfo().boundingBox;
  25869. if (!minVector) {
  25870. minVector = boundingBox.minimumWorld;
  25871. maxVector = boundingBox.maximumWorld;
  25872. }
  25873. else {
  25874. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25875. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25876. }
  25877. });
  25878. return {
  25879. min: minVector,
  25880. max: maxVector
  25881. };
  25882. };
  25883. /**
  25884. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25885. */
  25886. Mesh.Center = function (meshesOrMinMaxVector) {
  25887. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25888. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25889. };
  25890. /**
  25891. * Merge the array of meshes into a single mesh for performance reasons.
  25892. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25893. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25894. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25895. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25896. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25897. */
  25898. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25899. if (disposeSource === void 0) { disposeSource = true; }
  25900. var index;
  25901. if (!allow32BitsIndices) {
  25902. var totalVertices = 0;
  25903. // Counting vertices
  25904. for (index = 0; index < meshes.length; index++) {
  25905. if (meshes[index]) {
  25906. totalVertices += meshes[index].getTotalVertices();
  25907. if (totalVertices > 65536) {
  25908. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25909. return null;
  25910. }
  25911. }
  25912. }
  25913. }
  25914. // Merge
  25915. var vertexData;
  25916. var otherVertexData;
  25917. var indiceArray = new Array();
  25918. var source;
  25919. for (index = 0; index < meshes.length; index++) {
  25920. if (meshes[index]) {
  25921. meshes[index].computeWorldMatrix(true);
  25922. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25923. otherVertexData.transform(meshes[index].getWorldMatrix());
  25924. if (vertexData) {
  25925. vertexData.merge(otherVertexData);
  25926. }
  25927. else {
  25928. vertexData = otherVertexData;
  25929. source = meshes[index];
  25930. }
  25931. if (subdivideWithSubMeshes) {
  25932. indiceArray.push(meshes[index].getTotalIndices());
  25933. }
  25934. }
  25935. }
  25936. if (!meshSubclass) {
  25937. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25938. }
  25939. vertexData.applyToMesh(meshSubclass);
  25940. // Setting properties
  25941. meshSubclass.material = source.material;
  25942. meshSubclass.checkCollisions = source.checkCollisions;
  25943. // Cleaning
  25944. if (disposeSource) {
  25945. for (index = 0; index < meshes.length; index++) {
  25946. if (meshes[index]) {
  25947. meshes[index].dispose();
  25948. }
  25949. }
  25950. }
  25951. // Subdivide
  25952. if (subdivideWithSubMeshes) {
  25953. //-- Suppresions du submesh global
  25954. meshSubclass.releaseSubMeshes();
  25955. index = 0;
  25956. var offset = 0;
  25957. //-- aplique la subdivision en fonction du tableau d'indices
  25958. while (index < indiceArray.length) {
  25959. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25960. offset += indiceArray[index];
  25961. index++;
  25962. }
  25963. }
  25964. return meshSubclass;
  25965. };
  25966. return Mesh;
  25967. }(BABYLON.AbstractMesh));
  25968. // Consts
  25969. Mesh._FRONTSIDE = 0;
  25970. Mesh._BACKSIDE = 1;
  25971. Mesh._DOUBLESIDE = 2;
  25972. Mesh._DEFAULTSIDE = 0;
  25973. Mesh._NO_CAP = 0;
  25974. Mesh._CAP_START = 1;
  25975. Mesh._CAP_END = 2;
  25976. Mesh._CAP_ALL = 3;
  25977. BABYLON.Mesh = Mesh;
  25978. })(BABYLON || (BABYLON = {}));
  25979. //# sourceMappingURL=babylon.mesh.js.map
  25980. var BABYLON;
  25981. (function (BABYLON) {
  25982. var SubMesh = (function () {
  25983. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25984. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25985. this.materialIndex = materialIndex;
  25986. this.verticesStart = verticesStart;
  25987. this.verticesCount = verticesCount;
  25988. this.indexStart = indexStart;
  25989. this.indexCount = indexCount;
  25990. this._renderId = 0;
  25991. this._mesh = mesh;
  25992. this._renderingMesh = renderingMesh || mesh;
  25993. mesh.subMeshes.push(this);
  25994. this._trianglePlanes = [];
  25995. this._id = mesh.subMeshes.length - 1;
  25996. if (createBoundingBox) {
  25997. this.refreshBoundingInfo();
  25998. mesh.computeWorldMatrix(true);
  25999. }
  26000. }
  26001. Object.defineProperty(SubMesh.prototype, "effect", {
  26002. get: function () {
  26003. return this._materialEffect;
  26004. },
  26005. enumerable: true,
  26006. configurable: true
  26007. });
  26008. SubMesh.prototype.setEffect = function (effect, defines) {
  26009. if (this._materialEffect === effect) {
  26010. return;
  26011. }
  26012. this._materialDefines = defines;
  26013. this._materialEffect = effect;
  26014. };
  26015. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  26016. get: function () {
  26017. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  26018. },
  26019. enumerable: true,
  26020. configurable: true
  26021. });
  26022. /**
  26023. * Returns the submesh BoudingInfo object.
  26024. */
  26025. SubMesh.prototype.getBoundingInfo = function () {
  26026. if (this.IsGlobal) {
  26027. return this._mesh.getBoundingInfo();
  26028. }
  26029. return this._boundingInfo;
  26030. };
  26031. /**
  26032. * Sets the submesh BoundingInfo.
  26033. * Return the SubMesh.
  26034. */
  26035. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  26036. this._boundingInfo = boundingInfo;
  26037. return this;
  26038. };
  26039. /**
  26040. * Returns the mesh of the current submesh.
  26041. */
  26042. SubMesh.prototype.getMesh = function () {
  26043. return this._mesh;
  26044. };
  26045. /**
  26046. * Returns the rendering mesh of the submesh.
  26047. */
  26048. SubMesh.prototype.getRenderingMesh = function () {
  26049. return this._renderingMesh;
  26050. };
  26051. /**
  26052. * Returns the submesh material.
  26053. */
  26054. SubMesh.prototype.getMaterial = function () {
  26055. var rootMaterial = this._renderingMesh.material;
  26056. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  26057. var multiMaterial = rootMaterial;
  26058. return multiMaterial.getSubMaterial(this.materialIndex);
  26059. }
  26060. if (!rootMaterial) {
  26061. return this._mesh.getScene().defaultMaterial;
  26062. }
  26063. return rootMaterial;
  26064. };
  26065. // Methods
  26066. /**
  26067. * Sets a new updated BoundingInfo object to the submesh.
  26068. * Returns the SubMesh.
  26069. */
  26070. SubMesh.prototype.refreshBoundingInfo = function () {
  26071. this._lastColliderWorldVertices = null;
  26072. if (this.IsGlobal) {
  26073. return;
  26074. }
  26075. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26076. if (!data) {
  26077. this._boundingInfo = this._mesh._boundingInfo;
  26078. return;
  26079. }
  26080. var indices = this._renderingMesh.getIndices();
  26081. var extend;
  26082. //is this the only submesh?
  26083. if (this.indexStart === 0 && this.indexCount === indices.length) {
  26084. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  26085. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  26086. }
  26087. else {
  26088. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  26089. }
  26090. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26091. return this;
  26092. };
  26093. SubMesh.prototype._checkCollision = function (collider) {
  26094. return this.getBoundingInfo()._checkCollision(collider);
  26095. };
  26096. /**
  26097. * Updates the submesh BoundingInfo.
  26098. * Returns the Submesh.
  26099. */
  26100. SubMesh.prototype.updateBoundingInfo = function (world) {
  26101. if (!this.getBoundingInfo()) {
  26102. this.refreshBoundingInfo();
  26103. }
  26104. this.getBoundingInfo().update(world);
  26105. return this;
  26106. };
  26107. /**
  26108. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  26109. * Boolean returned.
  26110. */
  26111. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  26112. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  26113. };
  26114. /**
  26115. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  26116. * Boolean returned.
  26117. */
  26118. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  26119. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  26120. };
  26121. /**
  26122. * Renders the submesh.
  26123. * Returns it.
  26124. */
  26125. SubMesh.prototype.render = function (enableAlphaMode) {
  26126. this._renderingMesh.render(this, enableAlphaMode);
  26127. return this;
  26128. };
  26129. /**
  26130. * Returns a new Index Buffer.
  26131. * Type returned : WebGLBuffer.
  26132. */
  26133. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  26134. if (!this._linesIndexBuffer) {
  26135. var linesIndices = [];
  26136. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26137. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  26138. }
  26139. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  26140. this.linesIndexCount = linesIndices.length;
  26141. }
  26142. return this._linesIndexBuffer;
  26143. };
  26144. /**
  26145. * True is the passed Ray intersects the submesh bounding box.
  26146. * Boolean returned.
  26147. */
  26148. SubMesh.prototype.canIntersects = function (ray) {
  26149. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  26150. };
  26151. /**
  26152. * Returns an object IntersectionInfo.
  26153. */
  26154. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  26155. var intersectInfo = null;
  26156. // LineMesh first as it's also a Mesh...
  26157. if (this._mesh instanceof BABYLON.LinesMesh) {
  26158. var lineMesh = this._mesh;
  26159. // Line test
  26160. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  26161. var p0 = positions[indices[index]];
  26162. var p1 = positions[indices[index + 1]];
  26163. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  26164. if (length < 0) {
  26165. continue;
  26166. }
  26167. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  26168. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  26169. if (fastCheck) {
  26170. break;
  26171. }
  26172. }
  26173. }
  26174. }
  26175. else {
  26176. // Triangles test
  26177. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26178. var p0 = positions[indices[index]];
  26179. var p1 = positions[indices[index + 1]];
  26180. var p2 = positions[indices[index + 2]];
  26181. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  26182. if (currentIntersectInfo) {
  26183. if (currentIntersectInfo.distance < 0) {
  26184. continue;
  26185. }
  26186. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  26187. intersectInfo = currentIntersectInfo;
  26188. intersectInfo.faceId = index / 3;
  26189. if (fastCheck) {
  26190. break;
  26191. }
  26192. }
  26193. }
  26194. }
  26195. }
  26196. return intersectInfo;
  26197. };
  26198. // Clone
  26199. /**
  26200. * Creates a new Submesh from the passed Mesh.
  26201. */
  26202. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  26203. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  26204. if (!this.IsGlobal) {
  26205. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  26206. }
  26207. return result;
  26208. };
  26209. // Dispose
  26210. /**
  26211. * Disposes the Submesh.
  26212. * Returns nothing.
  26213. */
  26214. SubMesh.prototype.dispose = function () {
  26215. if (this._linesIndexBuffer) {
  26216. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  26217. this._linesIndexBuffer = null;
  26218. }
  26219. // Remove from mesh
  26220. var index = this._mesh.subMeshes.indexOf(this);
  26221. this._mesh.subMeshes.splice(index, 1);
  26222. };
  26223. // Statics
  26224. /**
  26225. * Creates a new Submesh from the passed parameters :
  26226. * - materialIndex (integer) : the index of the main mesh material.
  26227. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  26228. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  26229. * - mesh (Mesh) : the main mesh to create the submesh from.
  26230. * - renderingMesh (optional Mesh) : rendering mesh.
  26231. */
  26232. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  26233. var minVertexIndex = Number.MAX_VALUE;
  26234. var maxVertexIndex = -Number.MAX_VALUE;
  26235. renderingMesh = renderingMesh || mesh;
  26236. var indices = renderingMesh.getIndices();
  26237. for (var index = startIndex; index < startIndex + indexCount; index++) {
  26238. var vertexIndex = indices[index];
  26239. if (vertexIndex < minVertexIndex)
  26240. minVertexIndex = vertexIndex;
  26241. if (vertexIndex > maxVertexIndex)
  26242. maxVertexIndex = vertexIndex;
  26243. }
  26244. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  26245. };
  26246. return SubMesh;
  26247. }());
  26248. BABYLON.SubMesh = SubMesh;
  26249. })(BABYLON || (BABYLON = {}));
  26250. //# sourceMappingURL=babylon.subMesh.js.map
  26251. var BABYLON;
  26252. (function (BABYLON) {
  26253. var MeshBuilder = (function () {
  26254. function MeshBuilder() {
  26255. }
  26256. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  26257. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  26258. return BABYLON.Mesh.DOUBLESIDE;
  26259. }
  26260. if (orientation === undefined || orientation === null) {
  26261. return BABYLON.Mesh.FRONTSIDE;
  26262. }
  26263. return orientation;
  26264. };
  26265. /**
  26266. * Creates a box mesh.
  26267. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  26268. * The parameter `size` sets the size (float) of each box side (default 1).
  26269. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  26270. * 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).
  26271. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  26272. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26273. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26274. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26275. */
  26276. MeshBuilder.CreateBox = function (name, options, scene) {
  26277. var box = new BABYLON.Mesh(name, scene);
  26278. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26279. box.sideOrientation = options.sideOrientation;
  26280. var vertexData = BABYLON.VertexData.CreateBox(options);
  26281. vertexData.applyToMesh(box, options.updatable);
  26282. return box;
  26283. };
  26284. /**
  26285. * Creates a sphere mesh.
  26286. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  26287. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  26288. * 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`).
  26289. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  26290. * 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
  26291. * 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).
  26292. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26293. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26294. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26295. */
  26296. MeshBuilder.CreateSphere = function (name, options, scene) {
  26297. var sphere = new BABYLON.Mesh(name, scene);
  26298. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26299. sphere.sideOrientation = options.sideOrientation;
  26300. var vertexData = BABYLON.VertexData.CreateSphere(options);
  26301. vertexData.applyToMesh(sphere, options.updatable);
  26302. return sphere;
  26303. };
  26304. /**
  26305. * Creates a plane polygonal mesh. By default, this is a disc.
  26306. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  26307. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  26308. * 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.
  26309. * 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
  26310. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26311. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26312. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26313. */
  26314. MeshBuilder.CreateDisc = function (name, options, scene) {
  26315. var disc = new BABYLON.Mesh(name, scene);
  26316. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26317. disc.sideOrientation = options.sideOrientation;
  26318. var vertexData = BABYLON.VertexData.CreateDisc(options);
  26319. vertexData.applyToMesh(disc, options.updatable);
  26320. return disc;
  26321. };
  26322. /**
  26323. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  26324. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  26325. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  26326. * 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`).
  26327. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  26328. * 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.
  26329. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26330. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26331. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26332. */
  26333. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  26334. var sphere = new BABYLON.Mesh(name, scene);
  26335. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26336. sphere.sideOrientation = options.sideOrientation;
  26337. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  26338. vertexData.applyToMesh(sphere, options.updatable);
  26339. return sphere;
  26340. };
  26341. ;
  26342. /**
  26343. * Creates a ribbon mesh.
  26344. * 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.
  26345. *
  26346. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  26347. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  26348. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  26349. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  26350. * 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.
  26351. * 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.
  26352. * 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
  26353. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26354. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26355. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26356. * 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.
  26357. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  26358. * 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
  26359. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  26360. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  26361. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26362. */
  26363. MeshBuilder.CreateRibbon = function (name, options, scene) {
  26364. var pathArray = options.pathArray;
  26365. var closeArray = options.closeArray;
  26366. var closePath = options.closePath;
  26367. var offset = options.offset;
  26368. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26369. var instance = options.instance;
  26370. var updatable = options.updatable;
  26371. if (instance) {
  26372. // positionFunction : ribbon case
  26373. // only pathArray and sideOrientation parameters are taken into account for positions update
  26374. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  26375. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  26376. var positionFunction = function (positions) {
  26377. var minlg = pathArray[0].length;
  26378. var i = 0;
  26379. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  26380. for (var si = 1; si <= ns; si++) {
  26381. for (var p = 0; p < pathArray.length; p++) {
  26382. var path = pathArray[p];
  26383. var l = path.length;
  26384. minlg = (minlg < l) ? minlg : l;
  26385. var j = 0;
  26386. while (j < minlg) {
  26387. positions[i] = path[j].x;
  26388. positions[i + 1] = path[j].y;
  26389. positions[i + 2] = path[j].z;
  26390. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  26391. BABYLON.Tmp.Vector3[0].x = path[j].x;
  26392. }
  26393. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  26394. BABYLON.Tmp.Vector3[1].x = path[j].x;
  26395. }
  26396. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  26397. BABYLON.Tmp.Vector3[0].y = path[j].y;
  26398. }
  26399. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  26400. BABYLON.Tmp.Vector3[1].y = path[j].y;
  26401. }
  26402. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  26403. BABYLON.Tmp.Vector3[0].z = path[j].z;
  26404. }
  26405. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  26406. BABYLON.Tmp.Vector3[1].z = path[j].z;
  26407. }
  26408. j++;
  26409. i += 3;
  26410. }
  26411. if (instance._closePath) {
  26412. positions[i] = path[0].x;
  26413. positions[i + 1] = path[0].y;
  26414. positions[i + 2] = path[0].z;
  26415. i += 3;
  26416. }
  26417. }
  26418. }
  26419. };
  26420. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26421. positionFunction(positions);
  26422. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  26423. instance._boundingInfo.update(instance._worldMatrix);
  26424. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  26425. if (options.colors) {
  26426. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26427. for (var c = 0; c < options.colors.length; c++) {
  26428. colors[c * 4] = options.colors[c].r;
  26429. colors[c * 4 + 1] = options.colors[c].g;
  26430. colors[c * 4 + 2] = options.colors[c].b;
  26431. colors[c * 4 + 3] = options.colors[c].a;
  26432. }
  26433. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  26434. }
  26435. if (options.uvs) {
  26436. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26437. for (var i = 0; i < options.uvs.length; i++) {
  26438. uvs[i * 2] = options.uvs[i].x;
  26439. uvs[i * 2 + 1] = options.uvs[i].y;
  26440. }
  26441. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  26442. }
  26443. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  26444. var indices = instance.getIndices();
  26445. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26446. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  26447. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  26448. if (instance._closePath) {
  26449. var indexFirst = 0;
  26450. var indexLast = 0;
  26451. for (var p = 0; p < pathArray.length; p++) {
  26452. indexFirst = instance._idx[p] * 3;
  26453. if (p + 1 < pathArray.length) {
  26454. indexLast = (instance._idx[p + 1] - 1) * 3;
  26455. }
  26456. else {
  26457. indexLast = normals.length - 3;
  26458. }
  26459. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26460. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26461. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26462. normals[indexLast] = normals[indexFirst];
  26463. normals[indexLast + 1] = normals[indexFirst + 1];
  26464. normals[indexLast + 2] = normals[indexFirst + 2];
  26465. }
  26466. }
  26467. if (!(instance.areNormalsFrozen)) {
  26468. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  26469. }
  26470. }
  26471. return instance;
  26472. }
  26473. else {
  26474. var ribbon = new BABYLON.Mesh(name, scene);
  26475. ribbon.sideOrientation = sideOrientation;
  26476. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  26477. if (closePath) {
  26478. ribbon._idx = vertexData._idx;
  26479. }
  26480. ribbon._closePath = closePath;
  26481. ribbon._closeArray = closeArray;
  26482. vertexData.applyToMesh(ribbon, updatable);
  26483. return ribbon;
  26484. }
  26485. };
  26486. /**
  26487. * Creates a cylinder or a cone mesh.
  26488. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  26489. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  26490. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  26491. * 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.
  26492. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  26493. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  26494. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  26495. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  26496. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  26497. * 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).
  26498. * 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
  26499. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  26500. * 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
  26501. * 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.
  26502. * If `enclose` is false, a ring surface is one element.
  26503. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  26504. * 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
  26505. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26506. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26507. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26508. */
  26509. MeshBuilder.CreateCylinder = function (name, options, scene) {
  26510. var cylinder = new BABYLON.Mesh(name, scene);
  26511. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26512. cylinder.sideOrientation = options.sideOrientation;
  26513. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  26514. vertexData.applyToMesh(cylinder, options.updatable);
  26515. return cylinder;
  26516. };
  26517. /**
  26518. * Creates a torus mesh.
  26519. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  26520. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  26521. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  26522. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  26523. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26524. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26525. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26526. */
  26527. MeshBuilder.CreateTorus = function (name, options, scene) {
  26528. var torus = new BABYLON.Mesh(name, scene);
  26529. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26530. torus.sideOrientation = options.sideOrientation;
  26531. var vertexData = BABYLON.VertexData.CreateTorus(options);
  26532. vertexData.applyToMesh(torus, options.updatable);
  26533. return torus;
  26534. };
  26535. /**
  26536. * Creates a torus knot mesh.
  26537. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  26538. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  26539. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  26540. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  26541. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  26542. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26543. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26544. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26545. */
  26546. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  26547. var torusKnot = new BABYLON.Mesh(name, scene);
  26548. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26549. torusKnot.sideOrientation = options.sideOrientation;
  26550. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  26551. vertexData.applyToMesh(torusKnot, options.updatable);
  26552. return torusKnot;
  26553. };
  26554. /**
  26555. * Creates a line system mesh.
  26556. * A line system is a pool of many lines gathered in a single mesh.
  26557. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  26558. * 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.
  26559. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  26560. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  26561. * 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
  26562. * 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
  26563. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  26564. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26565. */
  26566. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  26567. var instance = options.instance;
  26568. var lines = options.lines;
  26569. if (instance) {
  26570. var positionFunction = function (positions) {
  26571. var i = 0;
  26572. for (var l = 0; l < lines.length; l++) {
  26573. var points = lines[l];
  26574. for (var p = 0; p < points.length; p++) {
  26575. positions[i] = points[p].x;
  26576. positions[i + 1] = points[p].y;
  26577. positions[i + 2] = points[p].z;
  26578. i += 3;
  26579. }
  26580. }
  26581. };
  26582. instance.updateMeshPositions(positionFunction, false);
  26583. return instance;
  26584. }
  26585. // line system creation
  26586. var lineSystem = new BABYLON.LinesMesh(name, scene);
  26587. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  26588. vertexData.applyToMesh(lineSystem, options.updatable);
  26589. return lineSystem;
  26590. };
  26591. /**
  26592. * Creates a line mesh.
  26593. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  26594. * 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.
  26595. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26596. * The parameter `points` is an array successive Vector3.
  26597. * 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
  26598. * When updating an instance, remember that only point positions can change, not the number of points.
  26599. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26600. */
  26601. MeshBuilder.CreateLines = function (name, options, scene) {
  26602. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  26603. return lines;
  26604. };
  26605. /**
  26606. * Creates a dashed line mesh.
  26607. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  26608. * 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.
  26609. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26610. * The parameter `points` is an array successive Vector3.
  26611. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  26612. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  26613. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  26614. * 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
  26615. * When updating an instance, remember that only point positions can change, not the number of points.
  26616. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26617. */
  26618. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  26619. var points = options.points;
  26620. var instance = options.instance;
  26621. var gapSize = options.gapSize;
  26622. var dashNb = options.dashNb;
  26623. var dashSize = options.dashSize;
  26624. if (instance) {
  26625. var positionFunction = function (positions) {
  26626. var curvect = BABYLON.Vector3.Zero();
  26627. var nbSeg = positions.length / 6;
  26628. var lg = 0;
  26629. var nb = 0;
  26630. var shft = 0;
  26631. var dashshft = 0;
  26632. var curshft = 0;
  26633. var p = 0;
  26634. var i = 0;
  26635. var j = 0;
  26636. for (i = 0; i < points.length - 1; i++) {
  26637. points[i + 1].subtractToRef(points[i], curvect);
  26638. lg += curvect.length();
  26639. }
  26640. shft = lg / nbSeg;
  26641. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  26642. for (i = 0; i < points.length - 1; i++) {
  26643. points[i + 1].subtractToRef(points[i], curvect);
  26644. nb = Math.floor(curvect.length() / shft);
  26645. curvect.normalize();
  26646. j = 0;
  26647. while (j < nb && p < positions.length) {
  26648. curshft = shft * j;
  26649. positions[p] = points[i].x + curshft * curvect.x;
  26650. positions[p + 1] = points[i].y + curshft * curvect.y;
  26651. positions[p + 2] = points[i].z + curshft * curvect.z;
  26652. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  26653. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  26654. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  26655. p += 6;
  26656. j++;
  26657. }
  26658. }
  26659. while (p < positions.length) {
  26660. positions[p] = points[i].x;
  26661. positions[p + 1] = points[i].y;
  26662. positions[p + 2] = points[i].z;
  26663. p += 3;
  26664. }
  26665. };
  26666. instance.updateMeshPositions(positionFunction, false);
  26667. return instance;
  26668. }
  26669. // dashed lines creation
  26670. var dashedLines = new BABYLON.LinesMesh(name, scene);
  26671. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  26672. vertexData.applyToMesh(dashedLines, options.updatable);
  26673. dashedLines.dashSize = dashSize;
  26674. dashedLines.gapSize = gapSize;
  26675. return dashedLines;
  26676. };
  26677. /**
  26678. * Creates an extruded shape mesh.
  26679. * 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.
  26680. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  26681. *
  26682. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26683. * 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
  26684. * extruded along the Z axis.
  26685. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26686. * 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.
  26687. * The parameter `scale` (float, default 1) is the value to scale the shape.
  26688. * 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
  26689. * 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
  26690. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26691. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26692. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26693. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26695. */
  26696. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  26697. var path = options.path;
  26698. var shape = options.shape;
  26699. var scale = options.scale || 1;
  26700. var rotation = options.rotation || 0;
  26701. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  26702. var updatable = options.updatable;
  26703. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26704. var instance = options.instance;
  26705. var invertUV = options.invertUV || false;
  26706. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  26707. };
  26708. /**
  26709. * Creates an custom extruded shape mesh.
  26710. * 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.
  26711. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  26712. *
  26713. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26714. * 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
  26715. * extruded along the Z axis.
  26716. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26717. * 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
  26718. * and the distance of this point from the begining of the path :
  26719. * ```javascript
  26720. * var rotationFunction = function(i, distance) {
  26721. * // do things
  26722. * return rotationValue; }
  26723. * ```
  26724. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  26725. * 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
  26726. * and the distance of this point from the begining of the path :
  26727. * ```javascript
  26728. * var scaleFunction = function(i, distance) {
  26729. * // do things
  26730. * return scaleValue;}
  26731. * ```
  26732. * It must returns a float value that will be the scale value applied to the shape on each path point.
  26733. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  26734. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  26735. * 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
  26736. * 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
  26737. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26738. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26739. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26740. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26741. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26742. */
  26743. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  26744. var path = options.path;
  26745. var shape = options.shape;
  26746. var scaleFunction = options.scaleFunction || (function () { return 1; });
  26747. var rotationFunction = options.rotationFunction || (function () { return 0; });
  26748. var ribbonCloseArray = options.ribbonCloseArray || false;
  26749. var ribbonClosePath = options.ribbonClosePath || false;
  26750. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  26751. var updatable = options.updatable;
  26752. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26753. var instance = options.instance;
  26754. var invertUV = options.invertUV || false;
  26755. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  26756. };
  26757. /**
  26758. * Creates lathe mesh.
  26759. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  26760. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  26761. *
  26762. * 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
  26763. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  26764. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  26765. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  26766. * 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.
  26767. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  26768. * 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
  26769. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26770. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26771. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26772. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26773. */
  26774. MeshBuilder.CreateLathe = function (name, options, scene) {
  26775. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  26776. var closed = (options.closed === undefined) ? true : options.closed;
  26777. var shape = options.shape;
  26778. var radius = options.radius || 1;
  26779. var tessellation = options.tessellation || 64;
  26780. var updatable = options.updatable;
  26781. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26782. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  26783. var pi2 = Math.PI * 2;
  26784. var paths = new Array();
  26785. var invertUV = options.invertUV || false;
  26786. var i = 0;
  26787. var p = 0;
  26788. var step = pi2 / tessellation * arc;
  26789. var rotated;
  26790. var path = new Array();
  26791. ;
  26792. for (i = 0; i <= tessellation; i++) {
  26793. var path = [];
  26794. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  26795. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  26796. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  26797. }
  26798. for (p = 0; p < shape.length; p++) {
  26799. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  26800. path.push(rotated);
  26801. }
  26802. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  26803. 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));
  26804. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  26805. }
  26806. paths.push(path);
  26807. }
  26808. // lathe ribbon
  26809. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  26810. return lathe;
  26811. };
  26812. /**
  26813. * Creates a plane mesh.
  26814. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  26815. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  26816. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  26817. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  26818. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26819. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26820. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26821. */
  26822. MeshBuilder.CreatePlane = function (name, options, scene) {
  26823. var plane = new BABYLON.Mesh(name, scene);
  26824. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26825. plane.sideOrientation = options.sideOrientation;
  26826. var vertexData = BABYLON.VertexData.CreatePlane(options);
  26827. vertexData.applyToMesh(plane, options.updatable);
  26828. if (options.sourcePlane) {
  26829. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  26830. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  26831. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  26832. plane.rotate(vectorProduct, product);
  26833. }
  26834. return plane;
  26835. };
  26836. /**
  26837. * Creates a ground mesh.
  26838. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  26839. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  26840. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  26841. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26842. */
  26843. MeshBuilder.CreateGround = function (name, options, scene) {
  26844. var ground = new BABYLON.GroundMesh(name, scene);
  26845. ground._setReady(false);
  26846. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26847. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26848. ground._width = options.width || 1;
  26849. ground._height = options.height || 1;
  26850. ground._maxX = ground._width / 2;
  26851. ground._maxZ = ground._height / 2;
  26852. ground._minX = -ground._maxX;
  26853. ground._minZ = -ground._maxZ;
  26854. var vertexData = BABYLON.VertexData.CreateGround(options);
  26855. vertexData.applyToMesh(ground, options.updatable);
  26856. ground._setReady(true);
  26857. return ground;
  26858. };
  26859. /**
  26860. * Creates a tiled ground mesh.
  26861. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  26862. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  26863. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  26864. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  26865. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  26866. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  26867. * numbers of subdivisions on the ground width and height of each tile.
  26868. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26869. */
  26870. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  26871. var tiledGround = new BABYLON.Mesh(name, scene);
  26872. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  26873. vertexData.applyToMesh(tiledGround, options.updatable);
  26874. return tiledGround;
  26875. };
  26876. /**
  26877. * Creates a ground mesh from a height map.
  26878. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  26879. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  26880. * The parameter `url` sets the URL of the height map image resource.
  26881. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  26882. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  26883. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  26884. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  26885. * 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.
  26886. * 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).
  26887. * This function is passed the newly built mesh :
  26888. * ```javascript
  26889. * function(mesh) { // do things
  26890. * return; }
  26891. * ```
  26892. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26893. */
  26894. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  26895. var width = options.width || 10.0;
  26896. var height = options.height || 10.0;
  26897. var subdivisions = options.subdivisions || 1 | 0;
  26898. var minHeight = options.minHeight || 0.0;
  26899. var maxHeight = options.maxHeight || 10.0;
  26900. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  26901. var updatable = options.updatable;
  26902. var onReady = options.onReady;
  26903. var ground = new BABYLON.GroundMesh(name, scene);
  26904. ground._subdivisionsX = subdivisions;
  26905. ground._subdivisionsY = subdivisions;
  26906. ground._width = width;
  26907. ground._height = height;
  26908. ground._maxX = ground._width / 2.0;
  26909. ground._maxZ = ground._height / 2.0;
  26910. ground._minX = -ground._maxX;
  26911. ground._minZ = -ground._maxZ;
  26912. ground._setReady(false);
  26913. var onload = function (img) {
  26914. // Getting height map data
  26915. var canvas = document.createElement("canvas");
  26916. var context = canvas.getContext("2d");
  26917. var bufferWidth = img.width;
  26918. var bufferHeight = img.height;
  26919. canvas.width = bufferWidth;
  26920. canvas.height = bufferHeight;
  26921. context.drawImage(img, 0, 0);
  26922. // Create VertexData from map data
  26923. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26924. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  26925. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  26926. width: width, height: height,
  26927. subdivisions: subdivisions,
  26928. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  26929. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  26930. });
  26931. vertexData.applyToMesh(ground, updatable);
  26932. ground._setReady(true);
  26933. //execute ready callback, if set
  26934. if (onReady) {
  26935. onReady(ground);
  26936. }
  26937. };
  26938. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26939. return ground;
  26940. };
  26941. /**
  26942. * Creates a tube mesh.
  26943. * 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.
  26944. *
  26945. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  26946. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  26947. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  26948. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  26949. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  26950. * 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.
  26951. * It must return a radius value (positive float) :
  26952. * ```javascript
  26953. * var radiusFunction = function(i, distance) {
  26954. * // do things
  26955. * return radius; }
  26956. * ```
  26957. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  26958. * 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
  26959. * 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
  26960. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26961. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26962. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26963. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26964. */
  26965. MeshBuilder.CreateTube = function (name, options, scene) {
  26966. var path = options.path;
  26967. var radius = options.radius || 1.0;
  26968. var tessellation = options.tessellation || 64 | 0;
  26969. var radiusFunction = options.radiusFunction;
  26970. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  26971. var invertUV = options.invertUV || false;
  26972. var updatable = options.updatable;
  26973. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26974. var instance = options.instance;
  26975. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  26976. // tube geometry
  26977. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  26978. var tangents = path3D.getTangents();
  26979. var normals = path3D.getNormals();
  26980. var distances = path3D.getDistances();
  26981. var pi2 = Math.PI * 2;
  26982. var step = pi2 / tessellation * arc;
  26983. var returnRadius = function () { return radius; };
  26984. var radiusFunctionFinal = radiusFunction || returnRadius;
  26985. var circlePath;
  26986. var rad;
  26987. var normal;
  26988. var rotated;
  26989. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  26990. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  26991. for (var i = 0; i < path.length; i++) {
  26992. rad = radiusFunctionFinal(i, distances[i]); // current radius
  26993. circlePath = Array(); // current circle array
  26994. normal = normals[i]; // current normal
  26995. for (var t = 0; t < tessellation; t++) {
  26996. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  26997. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  26998. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  26999. rotated.scaleInPlace(rad).addInPlace(path[i]);
  27000. circlePath[t] = rotated;
  27001. }
  27002. circlePaths[index] = circlePath;
  27003. index++;
  27004. }
  27005. // cap
  27006. var capPath = function (nbPoints, pathIndex) {
  27007. var pointCap = Array();
  27008. for (var i = 0; i < nbPoints; i++) {
  27009. pointCap.push(path[pathIndex]);
  27010. }
  27011. return pointCap;
  27012. };
  27013. switch (cap) {
  27014. case BABYLON.Mesh.NO_CAP:
  27015. break;
  27016. case BABYLON.Mesh.CAP_START:
  27017. circlePaths[0] = capPath(tessellation, 0);
  27018. circlePaths[1] = circlePaths[2].slice(0);
  27019. break;
  27020. case BABYLON.Mesh.CAP_END:
  27021. circlePaths[index] = circlePaths[index - 1].slice(0);
  27022. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  27023. break;
  27024. case BABYLON.Mesh.CAP_ALL:
  27025. circlePaths[0] = capPath(tessellation, 0);
  27026. circlePaths[1] = circlePaths[2].slice(0);
  27027. circlePaths[index] = circlePaths[index - 1].slice(0);
  27028. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  27029. break;
  27030. default:
  27031. break;
  27032. }
  27033. return circlePaths;
  27034. };
  27035. var path3D;
  27036. var pathArray;
  27037. if (instance) {
  27038. var arc = options.arc || instance.arc;
  27039. path3D = (instance.path3D).update(path);
  27040. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  27041. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  27042. instance.path3D = path3D;
  27043. instance.pathArray = pathArray;
  27044. instance.arc = arc;
  27045. return instance;
  27046. }
  27047. // tube creation
  27048. path3D = new BABYLON.Path3D(path);
  27049. var newPathArray = new Array();
  27050. cap = (cap < 0 || cap > 3) ? 0 : cap;
  27051. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  27052. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  27053. tube.pathArray = pathArray;
  27054. tube.path3D = path3D;
  27055. tube.tessellation = tessellation;
  27056. tube.cap = cap;
  27057. tube.arc = options.arc;
  27058. return tube;
  27059. };
  27060. /**
  27061. * Creates a polyhedron mesh.
  27062. *
  27063. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  27064. * 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
  27065. * to choose the wanted type.
  27066. * The parameter `size` (positive float, default 1) sets the polygon size.
  27067. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  27068. * 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`.
  27069. * 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
  27070. * 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)`).
  27071. * 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
  27072. * 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.
  27073. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27074. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27075. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27076. */
  27077. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  27078. var polyhedron = new BABYLON.Mesh(name, scene);
  27079. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  27080. polyhedron.sideOrientation = options.sideOrientation;
  27081. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  27082. vertexData.applyToMesh(polyhedron, options.updatable);
  27083. return polyhedron;
  27084. };
  27085. /**
  27086. * Creates a decal mesh.
  27087. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  27088. * 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.
  27089. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  27090. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  27091. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  27092. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  27093. */
  27094. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  27095. var indices = sourceMesh.getIndices();
  27096. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27097. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27098. var position = options.position || BABYLON.Vector3.Zero();
  27099. var normal = options.normal || BABYLON.Vector3.Up();
  27100. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  27101. var angle = options.angle || 0;
  27102. // Getting correct rotation
  27103. if (!normal) {
  27104. var target = new BABYLON.Vector3(0, 0, 1);
  27105. var camera = sourceMesh.getScene().activeCamera;
  27106. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  27107. normal = camera.globalPosition.subtract(cameraWorldTarget);
  27108. }
  27109. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  27110. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  27111. var pitch = Math.atan2(normal.y, len);
  27112. // Matrix
  27113. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  27114. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  27115. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  27116. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  27117. var vertexData = new BABYLON.VertexData();
  27118. vertexData.indices = [];
  27119. vertexData.positions = [];
  27120. vertexData.normals = [];
  27121. vertexData.uvs = [];
  27122. var currentVertexDataIndex = 0;
  27123. var extractDecalVector3 = function (indexId) {
  27124. var vertexId = indices[indexId];
  27125. var result = new BABYLON.PositionNormalVertex();
  27126. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  27127. // Send vector to decal local world
  27128. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  27129. // Get normal
  27130. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  27131. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  27132. return result;
  27133. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  27134. var clip = function (vertices, axis) {
  27135. if (vertices.length === 0) {
  27136. return vertices;
  27137. }
  27138. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  27139. var clipVertices = function (v0, v1) {
  27140. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  27141. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  27142. };
  27143. var result = new Array();
  27144. for (var index = 0; index < vertices.length; index += 3) {
  27145. var v1Out;
  27146. var v2Out;
  27147. var v3Out;
  27148. var total = 0;
  27149. var nV1, nV2, nV3, nV4;
  27150. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  27151. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  27152. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  27153. v1Out = d1 > 0;
  27154. v2Out = d2 > 0;
  27155. v3Out = d3 > 0;
  27156. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  27157. switch (total) {
  27158. case 0:
  27159. result.push(vertices[index]);
  27160. result.push(vertices[index + 1]);
  27161. result.push(vertices[index + 2]);
  27162. break;
  27163. case 1:
  27164. if (v1Out) {
  27165. nV1 = vertices[index + 1];
  27166. nV2 = vertices[index + 2];
  27167. nV3 = clipVertices(vertices[index], nV1);
  27168. nV4 = clipVertices(vertices[index], nV2);
  27169. }
  27170. if (v2Out) {
  27171. nV1 = vertices[index];
  27172. nV2 = vertices[index + 2];
  27173. nV3 = clipVertices(vertices[index + 1], nV1);
  27174. nV4 = clipVertices(vertices[index + 1], nV2);
  27175. result.push(nV3);
  27176. result.push(nV2.clone());
  27177. result.push(nV1.clone());
  27178. result.push(nV2.clone());
  27179. result.push(nV3.clone());
  27180. result.push(nV4);
  27181. break;
  27182. }
  27183. if (v3Out) {
  27184. nV1 = vertices[index];
  27185. nV2 = vertices[index + 1];
  27186. nV3 = clipVertices(vertices[index + 2], nV1);
  27187. nV4 = clipVertices(vertices[index + 2], nV2);
  27188. }
  27189. result.push(nV1.clone());
  27190. result.push(nV2.clone());
  27191. result.push(nV3);
  27192. result.push(nV4);
  27193. result.push(nV3.clone());
  27194. result.push(nV2.clone());
  27195. break;
  27196. case 2:
  27197. if (!v1Out) {
  27198. nV1 = vertices[index].clone();
  27199. nV2 = clipVertices(nV1, vertices[index + 1]);
  27200. nV3 = clipVertices(nV1, vertices[index + 2]);
  27201. result.push(nV1);
  27202. result.push(nV2);
  27203. result.push(nV3);
  27204. }
  27205. if (!v2Out) {
  27206. nV1 = vertices[index + 1].clone();
  27207. nV2 = clipVertices(nV1, vertices[index + 2]);
  27208. nV3 = clipVertices(nV1, vertices[index]);
  27209. result.push(nV1);
  27210. result.push(nV2);
  27211. result.push(nV3);
  27212. }
  27213. if (!v3Out) {
  27214. nV1 = vertices[index + 2].clone();
  27215. nV2 = clipVertices(nV1, vertices[index]);
  27216. nV3 = clipVertices(nV1, vertices[index + 1]);
  27217. result.push(nV1);
  27218. result.push(nV2);
  27219. result.push(nV3);
  27220. }
  27221. break;
  27222. case 3:
  27223. break;
  27224. }
  27225. }
  27226. return result;
  27227. };
  27228. for (var index = 0; index < indices.length; index += 3) {
  27229. var faceVertices = new Array();
  27230. faceVertices.push(extractDecalVector3(index));
  27231. faceVertices.push(extractDecalVector3(index + 1));
  27232. faceVertices.push(extractDecalVector3(index + 2));
  27233. // Clip
  27234. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  27235. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  27236. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  27237. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  27238. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  27239. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  27240. if (faceVertices.length === 0) {
  27241. continue;
  27242. }
  27243. // Add UVs and get back to world
  27244. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  27245. var vertex = faceVertices[vIndex];
  27246. //TODO check for Int32Array | Uint32Array | Uint16Array
  27247. vertexData.indices.push(currentVertexDataIndex);
  27248. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  27249. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  27250. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  27251. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  27252. currentVertexDataIndex++;
  27253. }
  27254. }
  27255. // Return mesh
  27256. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  27257. vertexData.applyToMesh(decal);
  27258. decal.position = position.clone();
  27259. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  27260. return decal;
  27261. };
  27262. // Privates
  27263. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  27264. // extrusion geometry
  27265. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  27266. var tangents = path3D.getTangents();
  27267. var normals = path3D.getNormals();
  27268. var binormals = path3D.getBinormals();
  27269. var distances = path3D.getDistances();
  27270. var angle = 0;
  27271. var returnScale = function () { return scale; };
  27272. var returnRotation = function () { return rotation; };
  27273. var rotate = custom ? rotateFunction : returnRotation;
  27274. var scl = custom ? scaleFunction : returnScale;
  27275. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  27276. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  27277. for (var i = 0; i < curve.length; i++) {
  27278. var shapePath = new Array();
  27279. var angleStep = rotate(i, distances[i]);
  27280. var scaleRatio = scl(i, distances[i]);
  27281. for (var p = 0; p < shape.length; p++) {
  27282. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  27283. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  27284. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  27285. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  27286. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  27287. shapePath[p] = rotated;
  27288. }
  27289. shapePaths[index] = shapePath;
  27290. angle += angleStep;
  27291. index++;
  27292. }
  27293. // cap
  27294. var capPath = function (shapePath) {
  27295. var pointCap = Array();
  27296. var barycenter = BABYLON.Vector3.Zero();
  27297. var i;
  27298. for (i = 0; i < shapePath.length; i++) {
  27299. barycenter.addInPlace(shapePath[i]);
  27300. }
  27301. barycenter.scaleInPlace(1.0 / shapePath.length);
  27302. for (i = 0; i < shapePath.length; i++) {
  27303. pointCap.push(barycenter);
  27304. }
  27305. return pointCap;
  27306. };
  27307. switch (cap) {
  27308. case BABYLON.Mesh.NO_CAP:
  27309. break;
  27310. case BABYLON.Mesh.CAP_START:
  27311. shapePaths[0] = capPath(shapePaths[2]);
  27312. shapePaths[1] = shapePaths[2];
  27313. break;
  27314. case BABYLON.Mesh.CAP_END:
  27315. shapePaths[index] = shapePaths[index - 1];
  27316. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  27317. break;
  27318. case BABYLON.Mesh.CAP_ALL:
  27319. shapePaths[0] = capPath(shapePaths[2]);
  27320. shapePaths[1] = shapePaths[2];
  27321. shapePaths[index] = shapePaths[index - 1];
  27322. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  27323. break;
  27324. default:
  27325. break;
  27326. }
  27327. return shapePaths;
  27328. };
  27329. var path3D;
  27330. var pathArray;
  27331. if (instance) {
  27332. path3D = (instance.path3D).update(curve);
  27333. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  27334. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  27335. return instance;
  27336. }
  27337. // extruded shape creation
  27338. path3D = new BABYLON.Path3D(curve);
  27339. var newShapePaths = new Array();
  27340. cap = (cap < 0 || cap > 3) ? 0 : cap;
  27341. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  27342. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  27343. extrudedGeneric.pathArray = pathArray;
  27344. extrudedGeneric.path3D = path3D;
  27345. extrudedGeneric.cap = cap;
  27346. return extrudedGeneric;
  27347. };
  27348. return MeshBuilder;
  27349. }());
  27350. BABYLON.MeshBuilder = MeshBuilder;
  27351. })(BABYLON || (BABYLON = {}));
  27352. //# sourceMappingURL=babylon.meshBuilder.js.map
  27353. var BABYLON;
  27354. (function (BABYLON) {
  27355. var BaseTexture = (function () {
  27356. function BaseTexture(scene) {
  27357. this._hasAlpha = false;
  27358. this.getAlphaFromRGB = false;
  27359. this.level = 1;
  27360. this.coordinatesIndex = 0;
  27361. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  27362. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  27363. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  27364. this.anisotropicFilteringLevel = 4;
  27365. this.isCube = false;
  27366. this.isRenderTarget = false;
  27367. this.animations = new Array();
  27368. /**
  27369. * An event triggered when the texture is disposed.
  27370. * @type {BABYLON.Observable}
  27371. */
  27372. this.onDisposeObservable = new BABYLON.Observable();
  27373. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27374. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27375. this._scene.textures.push(this);
  27376. this._uid = null;
  27377. }
  27378. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  27379. get: function () {
  27380. return this._hasAlpha;
  27381. },
  27382. set: function (value) {
  27383. if (this._hasAlpha === value) {
  27384. return;
  27385. }
  27386. this._hasAlpha = value;
  27387. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27388. },
  27389. enumerable: true,
  27390. configurable: true
  27391. });
  27392. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  27393. get: function () {
  27394. return this._coordinatesMode;
  27395. },
  27396. set: function (value) {
  27397. if (this._coordinatesMode === value) {
  27398. return;
  27399. }
  27400. this._coordinatesMode = value;
  27401. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27402. },
  27403. enumerable: true,
  27404. configurable: true
  27405. });
  27406. Object.defineProperty(BaseTexture.prototype, "uid", {
  27407. get: function () {
  27408. if (!this._uid) {
  27409. this._uid = BABYLON.Tools.RandomId();
  27410. }
  27411. return this._uid;
  27412. },
  27413. enumerable: true,
  27414. configurable: true
  27415. });
  27416. BaseTexture.prototype.toString = function () {
  27417. return this.name;
  27418. };
  27419. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  27420. set: function (callback) {
  27421. if (this._onDisposeObserver) {
  27422. this.onDisposeObservable.remove(this._onDisposeObserver);
  27423. }
  27424. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27425. },
  27426. enumerable: true,
  27427. configurable: true
  27428. });
  27429. BaseTexture.prototype.getScene = function () {
  27430. return this._scene;
  27431. };
  27432. BaseTexture.prototype.getTextureMatrix = function () {
  27433. return null;
  27434. };
  27435. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  27436. return null;
  27437. };
  27438. BaseTexture.prototype.getInternalTexture = function () {
  27439. return this._texture;
  27440. };
  27441. BaseTexture.prototype.isReady = function () {
  27442. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27443. return true;
  27444. }
  27445. if (this._texture) {
  27446. return this._texture.isReady;
  27447. }
  27448. return false;
  27449. };
  27450. BaseTexture.prototype.getSize = function () {
  27451. if (this._texture._width) {
  27452. return new BABYLON.Size(this._texture._width, this._texture._height);
  27453. }
  27454. if (this._texture._size) {
  27455. return new BABYLON.Size(this._texture._size, this._texture._size);
  27456. }
  27457. return BABYLON.Size.Zero();
  27458. };
  27459. BaseTexture.prototype.getBaseSize = function () {
  27460. if (!this.isReady() || !this._texture)
  27461. return BABYLON.Size.Zero();
  27462. if (this._texture._size) {
  27463. return new BABYLON.Size(this._texture._size, this._texture._size);
  27464. }
  27465. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  27466. };
  27467. BaseTexture.prototype.scale = function (ratio) {
  27468. };
  27469. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27470. get: function () {
  27471. return false;
  27472. },
  27473. enumerable: true,
  27474. configurable: true
  27475. });
  27476. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  27477. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27478. for (var index = 0; index < texturesCache.length; index++) {
  27479. var texturesCacheEntry = texturesCache[index];
  27480. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  27481. texturesCache.splice(index, 1);
  27482. return;
  27483. }
  27484. }
  27485. };
  27486. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27487. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27488. for (var index = 0; index < texturesCache.length; index++) {
  27489. var texturesCacheEntry = texturesCache[index];
  27490. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  27491. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27492. texturesCacheEntry.references++;
  27493. return texturesCacheEntry;
  27494. }
  27495. }
  27496. }
  27497. return null;
  27498. };
  27499. BaseTexture.prototype.delayLoad = function () {
  27500. };
  27501. BaseTexture.prototype.clone = function () {
  27502. return null;
  27503. };
  27504. BaseTexture.prototype.releaseInternalTexture = function () {
  27505. if (this._texture) {
  27506. this._scene.getEngine().releaseInternalTexture(this._texture);
  27507. delete this._texture;
  27508. }
  27509. };
  27510. BaseTexture.prototype.dispose = function () {
  27511. // Animations
  27512. this.getScene().stopAnimation(this);
  27513. // Remove from scene
  27514. this._scene._removePendingData(this);
  27515. var index = this._scene.textures.indexOf(this);
  27516. if (index >= 0) {
  27517. this._scene.textures.splice(index, 1);
  27518. }
  27519. if (this._texture === undefined) {
  27520. return;
  27521. }
  27522. // Release
  27523. this.releaseInternalTexture();
  27524. // Callback
  27525. this.onDisposeObservable.notifyObservers(this);
  27526. this.onDisposeObservable.clear();
  27527. };
  27528. BaseTexture.prototype.serialize = function () {
  27529. if (!this.name) {
  27530. return null;
  27531. }
  27532. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27533. // Animations
  27534. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27535. return serializationObject;
  27536. };
  27537. return BaseTexture;
  27538. }());
  27539. __decorate([
  27540. BABYLON.serialize()
  27541. ], BaseTexture.prototype, "name", void 0);
  27542. __decorate([
  27543. BABYLON.serialize("hasAlpha")
  27544. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27545. __decorate([
  27546. BABYLON.serialize()
  27547. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27548. __decorate([
  27549. BABYLON.serialize()
  27550. ], BaseTexture.prototype, "level", void 0);
  27551. __decorate([
  27552. BABYLON.serialize()
  27553. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27554. __decorate([
  27555. BABYLON.serialize("coordinatesMode")
  27556. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27557. __decorate([
  27558. BABYLON.serialize()
  27559. ], BaseTexture.prototype, "wrapU", void 0);
  27560. __decorate([
  27561. BABYLON.serialize()
  27562. ], BaseTexture.prototype, "wrapV", void 0);
  27563. __decorate([
  27564. BABYLON.serialize()
  27565. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27566. __decorate([
  27567. BABYLON.serialize()
  27568. ], BaseTexture.prototype, "isCube", void 0);
  27569. __decorate([
  27570. BABYLON.serialize()
  27571. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27572. BABYLON.BaseTexture = BaseTexture;
  27573. })(BABYLON || (BABYLON = {}));
  27574. //# sourceMappingURL=babylon.baseTexture.js.map
  27575. var BABYLON;
  27576. (function (BABYLON) {
  27577. var Texture = (function (_super) {
  27578. __extends(Texture, _super);
  27579. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27580. if (noMipmap === void 0) { noMipmap = false; }
  27581. if (invertY === void 0) { invertY = true; }
  27582. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27583. if (onLoad === void 0) { onLoad = null; }
  27584. if (onError === void 0) { onError = null; }
  27585. if (buffer === void 0) { buffer = null; }
  27586. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27587. var _this = _super.call(this, scene) || this;
  27588. _this.uOffset = 0;
  27589. _this.vOffset = 0;
  27590. _this.uScale = 1.0;
  27591. _this.vScale = 1.0;
  27592. _this.uAng = 0;
  27593. _this.vAng = 0;
  27594. _this.wAng = 0;
  27595. _this.name = url;
  27596. _this.url = url;
  27597. _this._noMipmap = noMipmap;
  27598. _this._invertY = invertY;
  27599. _this._samplingMode = samplingMode;
  27600. _this._buffer = buffer;
  27601. _this._deleteBuffer = deleteBuffer;
  27602. _this._format = format;
  27603. if (!url) {
  27604. return _this;
  27605. }
  27606. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  27607. var load = function () {
  27608. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  27609. _this.onLoadObservable.notifyObservers(true);
  27610. }
  27611. if (onLoad) {
  27612. onLoad();
  27613. }
  27614. };
  27615. if (!_this._texture) {
  27616. if (!scene.useDelayedTextureLoading) {
  27617. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  27618. if (deleteBuffer) {
  27619. delete _this._buffer;
  27620. }
  27621. }
  27622. else {
  27623. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27624. _this._delayedOnLoad = load;
  27625. _this._delayedOnError = onError;
  27626. }
  27627. }
  27628. else {
  27629. if (_this._texture.isReady) {
  27630. BABYLON.Tools.SetImmediate(function () { return load(); });
  27631. }
  27632. else {
  27633. _this._texture.onLoadedCallbacks.push(load);
  27634. }
  27635. }
  27636. return _this;
  27637. }
  27638. Object.defineProperty(Texture.prototype, "noMipmap", {
  27639. get: function () {
  27640. return this._noMipmap;
  27641. },
  27642. enumerable: true,
  27643. configurable: true
  27644. });
  27645. Texture.prototype.delayLoad = function () {
  27646. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27647. return;
  27648. }
  27649. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27650. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27651. if (!this._texture) {
  27652. 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);
  27653. if (this._deleteBuffer) {
  27654. delete this._buffer;
  27655. }
  27656. }
  27657. };
  27658. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27659. if (!this._texture) {
  27660. return;
  27661. }
  27662. this._samplingMode = samplingMode;
  27663. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27664. };
  27665. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27666. x *= this.uScale;
  27667. y *= this.vScale;
  27668. x -= 0.5 * this.uScale;
  27669. y -= 0.5 * this.vScale;
  27670. z -= 0.5;
  27671. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27672. t.x += 0.5 * this.uScale + this.uOffset;
  27673. t.y += 0.5 * this.vScale + this.vOffset;
  27674. t.z += 0.5;
  27675. };
  27676. Texture.prototype.getTextureMatrix = function () {
  27677. if (this.uOffset === this._cachedUOffset &&
  27678. this.vOffset === this._cachedVOffset &&
  27679. this.uScale === this._cachedUScale &&
  27680. this.vScale === this._cachedVScale &&
  27681. this.uAng === this._cachedUAng &&
  27682. this.vAng === this._cachedVAng &&
  27683. this.wAng === this._cachedWAng) {
  27684. return this._cachedTextureMatrix;
  27685. }
  27686. this._cachedUOffset = this.uOffset;
  27687. this._cachedVOffset = this.vOffset;
  27688. this._cachedUScale = this.uScale;
  27689. this._cachedVScale = this.vScale;
  27690. this._cachedUAng = this.uAng;
  27691. this._cachedVAng = this.vAng;
  27692. this._cachedWAng = this.wAng;
  27693. if (!this._cachedTextureMatrix) {
  27694. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27695. this._rowGenerationMatrix = new BABYLON.Matrix();
  27696. this._t0 = BABYLON.Vector3.Zero();
  27697. this._t1 = BABYLON.Vector3.Zero();
  27698. this._t2 = BABYLON.Vector3.Zero();
  27699. }
  27700. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27701. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27702. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27703. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27704. this._t1.subtractInPlace(this._t0);
  27705. this._t2.subtractInPlace(this._t0);
  27706. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27707. this._cachedTextureMatrix.m[0] = this._t1.x;
  27708. this._cachedTextureMatrix.m[1] = this._t1.y;
  27709. this._cachedTextureMatrix.m[2] = this._t1.z;
  27710. this._cachedTextureMatrix.m[4] = this._t2.x;
  27711. this._cachedTextureMatrix.m[5] = this._t2.y;
  27712. this._cachedTextureMatrix.m[6] = this._t2.z;
  27713. this._cachedTextureMatrix.m[8] = this._t0.x;
  27714. this._cachedTextureMatrix.m[9] = this._t0.y;
  27715. this._cachedTextureMatrix.m[10] = this._t0.z;
  27716. return this._cachedTextureMatrix;
  27717. };
  27718. Texture.prototype.getReflectionTextureMatrix = function () {
  27719. if (this.uOffset === this._cachedUOffset &&
  27720. this.vOffset === this._cachedVOffset &&
  27721. this.uScale === this._cachedUScale &&
  27722. this.vScale === this._cachedVScale &&
  27723. this.coordinatesMode === this._cachedCoordinatesMode) {
  27724. return this._cachedTextureMatrix;
  27725. }
  27726. if (!this._cachedTextureMatrix) {
  27727. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27728. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27729. }
  27730. this._cachedCoordinatesMode = this.coordinatesMode;
  27731. switch (this.coordinatesMode) {
  27732. case Texture.PLANAR_MODE:
  27733. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27734. this._cachedTextureMatrix[0] = this.uScale;
  27735. this._cachedTextureMatrix[5] = this.vScale;
  27736. this._cachedTextureMatrix[12] = this.uOffset;
  27737. this._cachedTextureMatrix[13] = this.vOffset;
  27738. break;
  27739. case Texture.PROJECTION_MODE:
  27740. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27741. this._projectionModeMatrix.m[0] = 0.5;
  27742. this._projectionModeMatrix.m[5] = -0.5;
  27743. this._projectionModeMatrix.m[10] = 0.0;
  27744. this._projectionModeMatrix.m[12] = 0.5;
  27745. this._projectionModeMatrix.m[13] = 0.5;
  27746. this._projectionModeMatrix.m[14] = 1.0;
  27747. this._projectionModeMatrix.m[15] = 1.0;
  27748. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27749. break;
  27750. default:
  27751. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27752. break;
  27753. }
  27754. return this._cachedTextureMatrix;
  27755. };
  27756. Texture.prototype.clone = function () {
  27757. var _this = this;
  27758. return BABYLON.SerializationHelper.Clone(function () {
  27759. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27760. }, this);
  27761. };
  27762. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27763. get: function () {
  27764. if (!this._onLoadObservarble) {
  27765. this._onLoadObservarble = new BABYLON.Observable();
  27766. }
  27767. return this._onLoadObservarble;
  27768. },
  27769. enumerable: true,
  27770. configurable: true
  27771. });
  27772. // Statics
  27773. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27774. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27775. if (onLoad === void 0) { onLoad = null; }
  27776. if (onError === void 0) { onError = null; }
  27777. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27778. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27779. };
  27780. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27781. if (parsedTexture.customType) {
  27782. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27783. return customTexture.Parse(parsedTexture, scene, rootUrl);
  27784. }
  27785. if (parsedTexture.isCube) {
  27786. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27787. }
  27788. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27789. return null;
  27790. }
  27791. var texture = BABYLON.SerializationHelper.Parse(function () {
  27792. if (parsedTexture.mirrorPlane) {
  27793. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  27794. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27795. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27796. return mirrorTexture;
  27797. }
  27798. else if (parsedTexture.isRenderTarget) {
  27799. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  27800. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27801. return renderTargetTexture;
  27802. }
  27803. else {
  27804. var texture;
  27805. if (parsedTexture.base64String) {
  27806. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  27807. }
  27808. else {
  27809. texture = new Texture(rootUrl + parsedTexture.name, scene);
  27810. }
  27811. return texture;
  27812. }
  27813. }, parsedTexture, scene);
  27814. // Animations
  27815. if (parsedTexture.animations) {
  27816. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27817. var parsedAnimation = parsedTexture.animations[animationIndex];
  27818. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27819. }
  27820. }
  27821. return texture;
  27822. };
  27823. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27824. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27825. if (noMipmap === void 0) { noMipmap = false; }
  27826. if (invertY === void 0) { invertY = true; }
  27827. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27828. if (onLoad === void 0) { onLoad = null; }
  27829. if (onError === void 0) { onError = null; }
  27830. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27831. if (name.substr(0, 5) !== "data:") {
  27832. name = "data:" + name;
  27833. }
  27834. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27835. };
  27836. return Texture;
  27837. }(BABYLON.BaseTexture));
  27838. // Constants
  27839. Texture.NEAREST_SAMPLINGMODE = 1;
  27840. Texture.BILINEAR_SAMPLINGMODE = 2;
  27841. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27842. Texture.EXPLICIT_MODE = 0;
  27843. Texture.SPHERICAL_MODE = 1;
  27844. Texture.PLANAR_MODE = 2;
  27845. Texture.CUBIC_MODE = 3;
  27846. Texture.PROJECTION_MODE = 4;
  27847. Texture.SKYBOX_MODE = 5;
  27848. Texture.INVCUBIC_MODE = 6;
  27849. Texture.EQUIRECTANGULAR_MODE = 7;
  27850. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27851. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27852. Texture.CLAMP_ADDRESSMODE = 0;
  27853. Texture.WRAP_ADDRESSMODE = 1;
  27854. Texture.MIRROR_ADDRESSMODE = 2;
  27855. __decorate([
  27856. BABYLON.serialize()
  27857. ], Texture.prototype, "url", void 0);
  27858. __decorate([
  27859. BABYLON.serialize()
  27860. ], Texture.prototype, "uOffset", void 0);
  27861. __decorate([
  27862. BABYLON.serialize()
  27863. ], Texture.prototype, "vOffset", void 0);
  27864. __decorate([
  27865. BABYLON.serialize()
  27866. ], Texture.prototype, "uScale", void 0);
  27867. __decorate([
  27868. BABYLON.serialize()
  27869. ], Texture.prototype, "vScale", void 0);
  27870. __decorate([
  27871. BABYLON.serialize()
  27872. ], Texture.prototype, "uAng", void 0);
  27873. __decorate([
  27874. BABYLON.serialize()
  27875. ], Texture.prototype, "vAng", void 0);
  27876. __decorate([
  27877. BABYLON.serialize()
  27878. ], Texture.prototype, "wAng", void 0);
  27879. BABYLON.Texture = Texture;
  27880. })(BABYLON || (BABYLON = {}));
  27881. //# sourceMappingURL=babylon.texture.js.map
  27882. var BABYLON;
  27883. (function (BABYLON) {
  27884. var CubeTexture = (function (_super) {
  27885. __extends(CubeTexture, _super);
  27886. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  27887. if (onLoad === void 0) { onLoad = null; }
  27888. if (onError === void 0) { onError = null; }
  27889. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27890. var _this = _super.call(this, scene) || this;
  27891. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  27892. _this.name = rootUrl;
  27893. _this.url = rootUrl;
  27894. _this._noMipmap = noMipmap;
  27895. _this.hasAlpha = false;
  27896. _this._format = format;
  27897. if (!rootUrl && !files) {
  27898. return _this;
  27899. }
  27900. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  27901. if (!files) {
  27902. if (!extensions) {
  27903. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  27904. }
  27905. files = [];
  27906. for (var index = 0; index < extensions.length; index++) {
  27907. files.push(rootUrl + extensions[index]);
  27908. }
  27909. _this._extensions = extensions;
  27910. }
  27911. _this._files = files;
  27912. if (!_this._texture) {
  27913. if (!scene.useDelayedTextureLoading) {
  27914. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  27915. }
  27916. else {
  27917. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27918. }
  27919. }
  27920. else if (onLoad) {
  27921. if (_this._texture.isReady) {
  27922. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  27923. }
  27924. else {
  27925. _this._texture.onLoadedCallbacks.push(onLoad);
  27926. }
  27927. }
  27928. _this.isCube = true;
  27929. _this._textureMatrix = BABYLON.Matrix.Identity();
  27930. return _this;
  27931. }
  27932. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  27933. return new CubeTexture("", scene, null, noMipmap, files);
  27934. };
  27935. // Methods
  27936. CubeTexture.prototype.delayLoad = function () {
  27937. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27938. return;
  27939. }
  27940. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27941. this._texture = this._getFromCache(this.url, this._noMipmap);
  27942. if (!this._texture) {
  27943. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  27944. }
  27945. };
  27946. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  27947. return this._textureMatrix;
  27948. };
  27949. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  27950. var texture = BABYLON.SerializationHelper.Parse(function () {
  27951. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  27952. }, parsedTexture, scene);
  27953. // Animations
  27954. if (parsedTexture.animations) {
  27955. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27956. var parsedAnimation = parsedTexture.animations[animationIndex];
  27957. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27958. }
  27959. }
  27960. return texture;
  27961. };
  27962. CubeTexture.prototype.clone = function () {
  27963. var _this = this;
  27964. return BABYLON.SerializationHelper.Clone(function () {
  27965. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  27966. }, this);
  27967. };
  27968. return CubeTexture;
  27969. }(BABYLON.BaseTexture));
  27970. BABYLON.CubeTexture = CubeTexture;
  27971. })(BABYLON || (BABYLON = {}));
  27972. //# sourceMappingURL=babylon.cubeTexture.js.map
  27973. var BABYLON;
  27974. (function (BABYLON) {
  27975. var RenderTargetTexture = (function (_super) {
  27976. __extends(RenderTargetTexture, _super);
  27977. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  27978. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  27979. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  27980. if (isCube === void 0) { isCube = false; }
  27981. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27982. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  27983. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  27984. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  27985. _this.isCube = isCube;
  27986. /**
  27987. * Use this list to define the list of mesh you want to render.
  27988. */
  27989. _this.renderList = new Array();
  27990. _this.renderParticles = true;
  27991. _this.renderSprites = false;
  27992. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  27993. // Events
  27994. /**
  27995. * An event triggered when the texture is unbind.
  27996. * @type {BABYLON.Observable}
  27997. */
  27998. _this.onAfterUnbindObservable = new BABYLON.Observable();
  27999. /**
  28000. * An event triggered before rendering the texture
  28001. * @type {BABYLON.Observable}
  28002. */
  28003. _this.onBeforeRenderObservable = new BABYLON.Observable();
  28004. /**
  28005. * An event triggered after rendering the texture
  28006. * @type {BABYLON.Observable}
  28007. */
  28008. _this.onAfterRenderObservable = new BABYLON.Observable();
  28009. /**
  28010. * An event triggered after the texture clear
  28011. * @type {BABYLON.Observable}
  28012. */
  28013. _this.onClearObservable = new BABYLON.Observable();
  28014. _this._currentRefreshId = -1;
  28015. _this._refreshRate = 1;
  28016. _this._samples = 1;
  28017. _this.name = name;
  28018. _this.isRenderTarget = true;
  28019. _this._size = size;
  28020. _this._generateMipMaps = generateMipMaps;
  28021. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  28022. _this._renderTargetOptions = {
  28023. generateMipMaps: generateMipMaps,
  28024. type: type,
  28025. samplingMode: samplingMode,
  28026. generateDepthBuffer: generateDepthBuffer,
  28027. generateStencilBuffer: generateStencilBuffer
  28028. };
  28029. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  28030. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28031. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28032. }
  28033. if (isCube) {
  28034. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  28035. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  28036. _this._textureMatrix = BABYLON.Matrix.Identity();
  28037. }
  28038. else {
  28039. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  28040. }
  28041. // Rendering groups
  28042. _this._renderingManager = new BABYLON.RenderingManager(scene);
  28043. return _this;
  28044. }
  28045. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  28046. get: function () {
  28047. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  28048. },
  28049. enumerable: true,
  28050. configurable: true
  28051. });
  28052. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  28053. get: function () {
  28054. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  28055. },
  28056. enumerable: true,
  28057. configurable: true
  28058. });
  28059. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  28060. get: function () {
  28061. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  28062. },
  28063. enumerable: true,
  28064. configurable: true
  28065. });
  28066. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  28067. set: function (callback) {
  28068. if (this._onAfterUnbindObserver) {
  28069. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  28070. }
  28071. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  28072. },
  28073. enumerable: true,
  28074. configurable: true
  28075. });
  28076. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  28077. set: function (callback) {
  28078. if (this._onBeforeRenderObserver) {
  28079. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  28080. }
  28081. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  28082. },
  28083. enumerable: true,
  28084. configurable: true
  28085. });
  28086. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  28087. set: function (callback) {
  28088. if (this._onAfterRenderObserver) {
  28089. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  28090. }
  28091. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  28092. },
  28093. enumerable: true,
  28094. configurable: true
  28095. });
  28096. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  28097. set: function (callback) {
  28098. if (this._onClearObserver) {
  28099. this.onClearObservable.remove(this._onClearObserver);
  28100. }
  28101. this._onClearObserver = this.onClearObservable.add(callback);
  28102. },
  28103. enumerable: true,
  28104. configurable: true
  28105. });
  28106. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  28107. get: function () {
  28108. return this._samples;
  28109. },
  28110. set: function (value) {
  28111. if (this._samples === value) {
  28112. return;
  28113. }
  28114. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  28115. },
  28116. enumerable: true,
  28117. configurable: true
  28118. });
  28119. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  28120. this._currentRefreshId = -1;
  28121. };
  28122. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  28123. get: function () {
  28124. return this._refreshRate;
  28125. },
  28126. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  28127. set: function (value) {
  28128. this._refreshRate = value;
  28129. this.resetRefreshCounter();
  28130. },
  28131. enumerable: true,
  28132. configurable: true
  28133. });
  28134. RenderTargetTexture.prototype._shouldRender = function () {
  28135. if (this._currentRefreshId === -1) {
  28136. this._currentRefreshId = 1;
  28137. return true;
  28138. }
  28139. if (this.refreshRate === this._currentRefreshId) {
  28140. this._currentRefreshId = 1;
  28141. return true;
  28142. }
  28143. this._currentRefreshId++;
  28144. return false;
  28145. };
  28146. RenderTargetTexture.prototype.isReady = function () {
  28147. if (!this.getScene().renderTargetsEnabled) {
  28148. return false;
  28149. }
  28150. return _super.prototype.isReady.call(this);
  28151. };
  28152. RenderTargetTexture.prototype.getRenderSize = function () {
  28153. return this._size;
  28154. };
  28155. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  28156. get: function () {
  28157. return true;
  28158. },
  28159. enumerable: true,
  28160. configurable: true
  28161. });
  28162. RenderTargetTexture.prototype.scale = function (ratio) {
  28163. var newSize = this._size * ratio;
  28164. this.resize(newSize);
  28165. };
  28166. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  28167. if (this.isCube) {
  28168. return this._textureMatrix;
  28169. }
  28170. return _super.prototype.getReflectionTextureMatrix.call(this);
  28171. };
  28172. RenderTargetTexture.prototype.resize = function (size) {
  28173. this.releaseInternalTexture();
  28174. if (this.isCube) {
  28175. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  28176. }
  28177. else {
  28178. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  28179. }
  28180. };
  28181. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  28182. var scene = this.getScene();
  28183. var engine = scene.getEngine();
  28184. if (this.useCameraPostProcesses !== undefined) {
  28185. useCameraPostProcess = this.useCameraPostProcesses;
  28186. }
  28187. if (this._waitingRenderList) {
  28188. this.renderList = [];
  28189. for (var index = 0; index < this._waitingRenderList.length; index++) {
  28190. var id = this._waitingRenderList[index];
  28191. this.renderList.push(scene.getMeshByID(id));
  28192. }
  28193. delete this._waitingRenderList;
  28194. }
  28195. // Is predicate defined?
  28196. if (this.renderListPredicate) {
  28197. this.renderList.splice(0); // Clear previous renderList
  28198. var sceneMeshes = this.getScene().meshes;
  28199. for (var index = 0; index < sceneMeshes.length; index++) {
  28200. var mesh = sceneMeshes[index];
  28201. if (this.renderListPredicate(mesh)) {
  28202. this.renderList.push(mesh);
  28203. }
  28204. }
  28205. }
  28206. if (this.renderList && this.renderList.length === 0) {
  28207. return;
  28208. }
  28209. // Set custom projection.
  28210. // Needs to be before binding to prevent changing the aspect ratio.
  28211. if (this.activeCamera) {
  28212. engine.setViewport(this.activeCamera.viewport);
  28213. if (this.activeCamera !== scene.activeCamera) {
  28214. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  28215. }
  28216. }
  28217. else {
  28218. engine.setViewport(scene.activeCamera.viewport);
  28219. }
  28220. // Prepare renderingManager
  28221. this._renderingManager.reset();
  28222. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  28223. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  28224. var sceneRenderId = scene.getRenderId();
  28225. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  28226. var mesh = currentRenderList[meshIndex];
  28227. if (mesh) {
  28228. if (!mesh.isReady()) {
  28229. // Reset _currentRefreshId
  28230. this.resetRefreshCounter();
  28231. continue;
  28232. }
  28233. mesh._preActivateForIntermediateRendering(sceneRenderId);
  28234. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  28235. mesh._activate(sceneRenderId);
  28236. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28237. var subMesh = mesh.subMeshes[subIndex];
  28238. scene._activeIndices.addCount(subMesh.indexCount, false);
  28239. this._renderingManager.dispatch(subMesh);
  28240. }
  28241. }
  28242. }
  28243. }
  28244. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  28245. var particleSystem = scene.particleSystems[particleIndex];
  28246. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  28247. continue;
  28248. }
  28249. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  28250. this._renderingManager.dispatchParticles(particleSystem);
  28251. }
  28252. }
  28253. if (this.isCube) {
  28254. for (var face = 0; face < 6; face++) {
  28255. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  28256. scene.incrementRenderId();
  28257. scene.resetCachedMaterial();
  28258. }
  28259. }
  28260. else {
  28261. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  28262. }
  28263. this.onAfterUnbindObservable.notifyObservers(this);
  28264. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  28265. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  28266. }
  28267. engine.setViewport(scene.activeCamera.viewport);
  28268. scene.resetCachedMaterial();
  28269. };
  28270. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  28271. var _this = this;
  28272. var scene = this.getScene();
  28273. var engine = scene.getEngine();
  28274. // Bind
  28275. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  28276. if (this.isCube) {
  28277. engine.bindFramebuffer(this._texture, faceIndex);
  28278. }
  28279. else {
  28280. engine.bindFramebuffer(this._texture);
  28281. }
  28282. }
  28283. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  28284. // Clear
  28285. if (this.onClearObservable.hasObservers()) {
  28286. this.onClearObservable.notifyObservers(engine);
  28287. }
  28288. else {
  28289. engine.clear(scene.clearColor, true, true, true);
  28290. }
  28291. if (!this._doNotChangeAspectRatio) {
  28292. scene.updateTransformMatrix(true);
  28293. }
  28294. // Render
  28295. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  28296. if (useCameraPostProcess) {
  28297. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  28298. }
  28299. if (!this._doNotChangeAspectRatio) {
  28300. scene.updateTransformMatrix(true);
  28301. }
  28302. // Dump ?
  28303. if (dumpForDebug) {
  28304. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  28305. }
  28306. // Unbind
  28307. if (!this.isCube || faceIndex === 5) {
  28308. if (this.isCube) {
  28309. if (faceIndex === 5) {
  28310. engine.generateMipMapsForCubemap(this._texture);
  28311. }
  28312. }
  28313. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  28314. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  28315. });
  28316. }
  28317. else {
  28318. this.onAfterRenderObservable.notifyObservers(faceIndex);
  28319. }
  28320. };
  28321. /**
  28322. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28323. * This allowed control for front to back rendering or reversly depending of the special needs.
  28324. *
  28325. * @param renderingGroupId The rendering group id corresponding to its index
  28326. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28327. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28328. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28329. */
  28330. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28331. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28332. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28333. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28334. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28335. };
  28336. /**
  28337. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28338. *
  28339. * @param renderingGroupId The rendering group id corresponding to its index
  28340. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28341. */
  28342. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  28343. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  28344. };
  28345. RenderTargetTexture.prototype.clone = function () {
  28346. var textureSize = this.getSize();
  28347. 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);
  28348. // Base texture
  28349. newTexture.hasAlpha = this.hasAlpha;
  28350. newTexture.level = this.level;
  28351. // RenderTarget Texture
  28352. newTexture.coordinatesMode = this.coordinatesMode;
  28353. newTexture.renderList = this.renderList.slice(0);
  28354. return newTexture;
  28355. };
  28356. RenderTargetTexture.prototype.serialize = function () {
  28357. if (!this.name) {
  28358. return null;
  28359. }
  28360. var serializationObject = _super.prototype.serialize.call(this);
  28361. serializationObject.renderTargetSize = this.getRenderSize();
  28362. serializationObject.renderList = [];
  28363. for (var index = 0; index < this.renderList.length; index++) {
  28364. serializationObject.renderList.push(this.renderList[index].id);
  28365. }
  28366. return serializationObject;
  28367. };
  28368. return RenderTargetTexture;
  28369. }(BABYLON.Texture));
  28370. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  28371. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  28372. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  28373. BABYLON.RenderTargetTexture = RenderTargetTexture;
  28374. })(BABYLON || (BABYLON = {}));
  28375. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  28376. var BABYLON;
  28377. (function (BABYLON) {
  28378. var ProceduralTexture = (function (_super) {
  28379. __extends(ProceduralTexture, _super);
  28380. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  28381. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28382. if (isCube === void 0) { isCube = false; }
  28383. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  28384. _this.isCube = isCube;
  28385. _this.isEnabled = true;
  28386. _this._currentRefreshId = -1;
  28387. _this._refreshRate = 1;
  28388. _this._vertexBuffers = {};
  28389. _this._uniforms = new Array();
  28390. _this._samplers = new Array();
  28391. _this._textures = new Array();
  28392. _this._floats = new Array();
  28393. _this._floatsArrays = {};
  28394. _this._colors3 = new Array();
  28395. _this._colors4 = new Array();
  28396. _this._vectors2 = new Array();
  28397. _this._vectors3 = new Array();
  28398. _this._matrices = new Array();
  28399. _this._fallbackTextureUsed = false;
  28400. scene._proceduralTextures.push(_this);
  28401. _this.name = name;
  28402. _this.isRenderTarget = true;
  28403. _this._size = size;
  28404. _this._generateMipMaps = generateMipMaps;
  28405. _this.setFragment(fragment);
  28406. _this._fallbackTexture = fallbackTexture;
  28407. var engine = scene.getEngine();
  28408. if (isCube) {
  28409. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  28410. _this.setFloat("face", 0);
  28411. }
  28412. else {
  28413. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  28414. }
  28415. // VBO
  28416. var vertices = [];
  28417. vertices.push(1, 1);
  28418. vertices.push(-1, 1);
  28419. vertices.push(-1, -1);
  28420. vertices.push(1, -1);
  28421. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28422. // Indices
  28423. var indices = [];
  28424. indices.push(0);
  28425. indices.push(1);
  28426. indices.push(2);
  28427. indices.push(0);
  28428. indices.push(2);
  28429. indices.push(3);
  28430. _this._indexBuffer = engine.createIndexBuffer(indices);
  28431. return _this;
  28432. }
  28433. ProceduralTexture.prototype.reset = function () {
  28434. if (this._effect === undefined) {
  28435. return;
  28436. }
  28437. var engine = this.getScene().getEngine();
  28438. engine._releaseEffect(this._effect);
  28439. };
  28440. ProceduralTexture.prototype.isReady = function () {
  28441. var _this = this;
  28442. var engine = this.getScene().getEngine();
  28443. var shaders;
  28444. if (!this._fragment) {
  28445. return false;
  28446. }
  28447. if (this._fallbackTextureUsed) {
  28448. return true;
  28449. }
  28450. if (this._fragment.fragmentElement !== undefined) {
  28451. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  28452. }
  28453. else {
  28454. shaders = { vertex: "procedural", fragment: this._fragment };
  28455. }
  28456. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  28457. _this.releaseInternalTexture();
  28458. if (_this._fallbackTexture) {
  28459. _this._texture = _this._fallbackTexture._texture;
  28460. _this._texture.references++;
  28461. }
  28462. _this._fallbackTextureUsed = true;
  28463. });
  28464. return this._effect.isReady();
  28465. };
  28466. ProceduralTexture.prototype.resetRefreshCounter = function () {
  28467. this._currentRefreshId = -1;
  28468. };
  28469. ProceduralTexture.prototype.setFragment = function (fragment) {
  28470. this._fragment = fragment;
  28471. };
  28472. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  28473. get: function () {
  28474. return this._refreshRate;
  28475. },
  28476. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  28477. set: function (value) {
  28478. this._refreshRate = value;
  28479. this.resetRefreshCounter();
  28480. },
  28481. enumerable: true,
  28482. configurable: true
  28483. });
  28484. ProceduralTexture.prototype._shouldRender = function () {
  28485. if (!this.isEnabled || !this.isReady() || !this._texture) {
  28486. return false;
  28487. }
  28488. if (this._fallbackTextureUsed) {
  28489. return false;
  28490. }
  28491. if (this._currentRefreshId === -1) {
  28492. this._currentRefreshId = 1;
  28493. return true;
  28494. }
  28495. if (this.refreshRate === this._currentRefreshId) {
  28496. this._currentRefreshId = 1;
  28497. return true;
  28498. }
  28499. this._currentRefreshId++;
  28500. return false;
  28501. };
  28502. ProceduralTexture.prototype.getRenderSize = function () {
  28503. return this._size;
  28504. };
  28505. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  28506. if (this._fallbackTextureUsed) {
  28507. return;
  28508. }
  28509. this.releaseInternalTexture();
  28510. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  28511. };
  28512. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  28513. if (this._uniforms.indexOf(uniformName) === -1) {
  28514. this._uniforms.push(uniformName);
  28515. }
  28516. };
  28517. ProceduralTexture.prototype.setTexture = function (name, texture) {
  28518. if (this._samplers.indexOf(name) === -1) {
  28519. this._samplers.push(name);
  28520. }
  28521. this._textures[name] = texture;
  28522. return this;
  28523. };
  28524. ProceduralTexture.prototype.setFloat = function (name, value) {
  28525. this._checkUniform(name);
  28526. this._floats[name] = value;
  28527. return this;
  28528. };
  28529. ProceduralTexture.prototype.setFloats = function (name, value) {
  28530. this._checkUniform(name);
  28531. this._floatsArrays[name] = value;
  28532. return this;
  28533. };
  28534. ProceduralTexture.prototype.setColor3 = function (name, value) {
  28535. this._checkUniform(name);
  28536. this._colors3[name] = value;
  28537. return this;
  28538. };
  28539. ProceduralTexture.prototype.setColor4 = function (name, value) {
  28540. this._checkUniform(name);
  28541. this._colors4[name] = value;
  28542. return this;
  28543. };
  28544. ProceduralTexture.prototype.setVector2 = function (name, value) {
  28545. this._checkUniform(name);
  28546. this._vectors2[name] = value;
  28547. return this;
  28548. };
  28549. ProceduralTexture.prototype.setVector3 = function (name, value) {
  28550. this._checkUniform(name);
  28551. this._vectors3[name] = value;
  28552. return this;
  28553. };
  28554. ProceduralTexture.prototype.setMatrix = function (name, value) {
  28555. this._checkUniform(name);
  28556. this._matrices[name] = value;
  28557. return this;
  28558. };
  28559. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  28560. var scene = this.getScene();
  28561. var engine = scene.getEngine();
  28562. // Render
  28563. engine.enableEffect(this._effect);
  28564. engine.setState(false);
  28565. // Texture
  28566. for (var name in this._textures) {
  28567. this._effect.setTexture(name, this._textures[name]);
  28568. }
  28569. // Float
  28570. for (name in this._floats) {
  28571. this._effect.setFloat(name, this._floats[name]);
  28572. }
  28573. // Floats
  28574. for (name in this._floatsArrays) {
  28575. this._effect.setArray(name, this._floatsArrays[name]);
  28576. }
  28577. // Color3
  28578. for (name in this._colors3) {
  28579. this._effect.setColor3(name, this._colors3[name]);
  28580. }
  28581. // Color4
  28582. for (name in this._colors4) {
  28583. var color = this._colors4[name];
  28584. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28585. }
  28586. // Vector2
  28587. for (name in this._vectors2) {
  28588. this._effect.setVector2(name, this._vectors2[name]);
  28589. }
  28590. // Vector3
  28591. for (name in this._vectors3) {
  28592. this._effect.setVector3(name, this._vectors3[name]);
  28593. }
  28594. // Matrix
  28595. for (name in this._matrices) {
  28596. this._effect.setMatrix(name, this._matrices[name]);
  28597. }
  28598. if (this.isCube) {
  28599. for (var face = 0; face < 6; face++) {
  28600. engine.bindFramebuffer(this._texture, face);
  28601. // VBOs
  28602. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  28603. this._effect.setFloat("face", face);
  28604. // Clear
  28605. engine.clear(scene.clearColor, true, true, true);
  28606. // Draw order
  28607. engine.draw(true, 0, 6);
  28608. // Mipmaps
  28609. if (face === 5) {
  28610. engine.generateMipMapsForCubemap(this._texture);
  28611. }
  28612. }
  28613. }
  28614. else {
  28615. engine.bindFramebuffer(this._texture);
  28616. // VBOs
  28617. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  28618. // Clear
  28619. engine.clear(scene.clearColor, true, true, true);
  28620. // Draw order
  28621. engine.draw(true, 0, 6);
  28622. }
  28623. // Unbind
  28624. engine.unBindFramebuffer(this._texture, this.isCube);
  28625. if (this.onGenerated) {
  28626. this.onGenerated();
  28627. }
  28628. };
  28629. ProceduralTexture.prototype.clone = function () {
  28630. var textureSize = this.getSize();
  28631. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  28632. // Base texture
  28633. newTexture.hasAlpha = this.hasAlpha;
  28634. newTexture.level = this.level;
  28635. // RenderTarget Texture
  28636. newTexture.coordinatesMode = this.coordinatesMode;
  28637. return newTexture;
  28638. };
  28639. ProceduralTexture.prototype.dispose = function () {
  28640. var index = this.getScene()._proceduralTextures.indexOf(this);
  28641. if (index >= 0) {
  28642. this.getScene()._proceduralTextures.splice(index, 1);
  28643. }
  28644. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28645. if (vertexBuffer) {
  28646. vertexBuffer.dispose();
  28647. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28648. }
  28649. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  28650. this._indexBuffer = null;
  28651. }
  28652. _super.prototype.dispose.call(this);
  28653. };
  28654. return ProceduralTexture;
  28655. }(BABYLON.Texture));
  28656. BABYLON.ProceduralTexture = ProceduralTexture;
  28657. })(BABYLON || (BABYLON = {}));
  28658. //# sourceMappingURL=babylon.proceduralTexture.js.map
  28659. /// <reference path="babylon.renderTargetTexture.ts" />
  28660. var BABYLON;
  28661. (function (BABYLON) {
  28662. var MirrorTexture = (function (_super) {
  28663. __extends(MirrorTexture, _super);
  28664. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  28665. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  28666. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  28667. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  28668. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  28669. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  28670. _this._transformMatrix = BABYLON.Matrix.Zero();
  28671. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  28672. _this.onBeforeRenderObservable.add(function () {
  28673. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  28674. _this._savedViewMatrix = scene.getViewMatrix();
  28675. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  28676. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  28677. scene.clipPlane = _this.mirrorPlane;
  28678. scene.getEngine().cullBackFaces = false;
  28679. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  28680. });
  28681. _this.onAfterRenderObservable.add(function () {
  28682. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  28683. scene.getEngine().cullBackFaces = true;
  28684. scene._mirroredCameraPosition = null;
  28685. delete scene.clipPlane;
  28686. });
  28687. return _this;
  28688. }
  28689. MirrorTexture.prototype.clone = function () {
  28690. var textureSize = this.getSize();
  28691. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  28692. // Base texture
  28693. newTexture.hasAlpha = this.hasAlpha;
  28694. newTexture.level = this.level;
  28695. // Mirror Texture
  28696. newTexture.mirrorPlane = this.mirrorPlane.clone();
  28697. newTexture.renderList = this.renderList.slice(0);
  28698. return newTexture;
  28699. };
  28700. MirrorTexture.prototype.serialize = function () {
  28701. if (!this.name) {
  28702. return null;
  28703. }
  28704. var serializationObject = _super.prototype.serialize.call(this);
  28705. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  28706. return serializationObject;
  28707. };
  28708. return MirrorTexture;
  28709. }(BABYLON.RenderTargetTexture));
  28710. BABYLON.MirrorTexture = MirrorTexture;
  28711. })(BABYLON || (BABYLON = {}));
  28712. //# sourceMappingURL=babylon.mirrorTexture.js.map
  28713. /// <reference path="babylon.renderTargetTexture.ts" />
  28714. var BABYLON;
  28715. (function (BABYLON) {
  28716. /**
  28717. * Creates a refraction texture used by refraction channel of the standard material.
  28718. * @param name the texture name
  28719. * @param size size of the underlying texture
  28720. * @param scene root scene
  28721. */
  28722. var RefractionTexture = (function (_super) {
  28723. __extends(RefractionTexture, _super);
  28724. function RefractionTexture(name, size, scene, generateMipMaps) {
  28725. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  28726. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  28727. _this.depth = 2.0;
  28728. _this.onBeforeRenderObservable.add(function () {
  28729. scene.clipPlane = _this.refractionPlane;
  28730. });
  28731. _this.onAfterRenderObservable.add(function () {
  28732. delete scene.clipPlane;
  28733. });
  28734. return _this;
  28735. }
  28736. RefractionTexture.prototype.clone = function () {
  28737. var textureSize = this.getSize();
  28738. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  28739. // Base texture
  28740. newTexture.hasAlpha = this.hasAlpha;
  28741. newTexture.level = this.level;
  28742. // Refraction Texture
  28743. newTexture.refractionPlane = this.refractionPlane.clone();
  28744. newTexture.renderList = this.renderList.slice(0);
  28745. newTexture.depth = this.depth;
  28746. return newTexture;
  28747. };
  28748. RefractionTexture.prototype.serialize = function () {
  28749. if (!this.name) {
  28750. return null;
  28751. }
  28752. var serializationObject = _super.prototype.serialize.call(this);
  28753. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  28754. serializationObject.depth = this.depth;
  28755. return serializationObject;
  28756. };
  28757. return RefractionTexture;
  28758. }(BABYLON.RenderTargetTexture));
  28759. BABYLON.RefractionTexture = RefractionTexture;
  28760. })(BABYLON || (BABYLON = {}));
  28761. //# sourceMappingURL=babylon.refractionTexture.js.map
  28762. /// <reference path="babylon.texture.ts" />
  28763. var BABYLON;
  28764. (function (BABYLON) {
  28765. var DynamicTexture = (function (_super) {
  28766. __extends(DynamicTexture, _super);
  28767. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  28768. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28769. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  28770. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  28771. _this.name = name;
  28772. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28773. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28774. _this._generateMipMaps = generateMipMaps;
  28775. if (options.getContext) {
  28776. _this._canvas = options;
  28777. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  28778. }
  28779. else {
  28780. _this._canvas = document.createElement("canvas");
  28781. if (options.width) {
  28782. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  28783. }
  28784. else {
  28785. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  28786. }
  28787. }
  28788. var textureSize = _this.getSize();
  28789. _this._canvas.width = textureSize.width;
  28790. _this._canvas.height = textureSize.height;
  28791. _this._context = _this._canvas.getContext("2d");
  28792. return _this;
  28793. }
  28794. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  28795. get: function () {
  28796. return true;
  28797. },
  28798. enumerable: true,
  28799. configurable: true
  28800. });
  28801. DynamicTexture.prototype.scale = function (ratio) {
  28802. var textureSize = this.getSize();
  28803. textureSize.width *= ratio;
  28804. textureSize.height *= ratio;
  28805. this._canvas.width = textureSize.width;
  28806. this._canvas.height = textureSize.height;
  28807. this.releaseInternalTexture();
  28808. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  28809. };
  28810. DynamicTexture.prototype.getContext = function () {
  28811. return this._context;
  28812. };
  28813. DynamicTexture.prototype.clear = function () {
  28814. var size = this.getSize();
  28815. this._context.fillRect(0, 0, size.width, size.height);
  28816. };
  28817. DynamicTexture.prototype.update = function (invertY) {
  28818. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  28819. };
  28820. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  28821. if (update === void 0) { update = true; }
  28822. var size = this.getSize();
  28823. if (clearColor) {
  28824. this._context.fillStyle = clearColor;
  28825. this._context.fillRect(0, 0, size.width, size.height);
  28826. }
  28827. this._context.font = font;
  28828. if (x === null || x === undefined) {
  28829. var textSize = this._context.measureText(text);
  28830. x = (size.width - textSize.width) / 2;
  28831. }
  28832. if (y === null || y === undefined) {
  28833. var fontSize = parseInt((font.replace(/\D/g, '')));
  28834. ;
  28835. y = (size.height / 2) + (fontSize / 3.65);
  28836. }
  28837. this._context.fillStyle = color;
  28838. this._context.fillText(text, x, y);
  28839. if (update) {
  28840. this.update(invertY);
  28841. }
  28842. };
  28843. DynamicTexture.prototype.clone = function () {
  28844. var textureSize = this.getSize();
  28845. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  28846. // Base texture
  28847. newTexture.hasAlpha = this.hasAlpha;
  28848. newTexture.level = this.level;
  28849. // Dynamic Texture
  28850. newTexture.wrapU = this.wrapU;
  28851. newTexture.wrapV = this.wrapV;
  28852. return newTexture;
  28853. };
  28854. return DynamicTexture;
  28855. }(BABYLON.Texture));
  28856. BABYLON.DynamicTexture = DynamicTexture;
  28857. })(BABYLON || (BABYLON = {}));
  28858. //# sourceMappingURL=babylon.dynamicTexture.js.map
  28859. var BABYLON;
  28860. (function (BABYLON) {
  28861. var VideoTexture = (function (_super) {
  28862. __extends(VideoTexture, _super);
  28863. /**
  28864. * Creates a video texture.
  28865. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  28866. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  28867. * @param {BABYLON.Scene} scene is obviously the current scene.
  28868. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  28869. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  28870. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  28871. */
  28872. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  28873. if (generateMipMaps === void 0) { generateMipMaps = false; }
  28874. if (invertY === void 0) { invertY = false; }
  28875. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28876. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  28877. _this._autoLaunch = true;
  28878. var urls;
  28879. _this.name = name;
  28880. if (urlsOrVideo instanceof HTMLVideoElement) {
  28881. _this.video = urlsOrVideo;
  28882. }
  28883. else {
  28884. urls = urlsOrVideo;
  28885. _this.video = document.createElement("video");
  28886. _this.video.autoplay = false;
  28887. _this.video.loop = true;
  28888. }
  28889. _this._generateMipMaps = generateMipMaps;
  28890. _this._samplingMode = samplingMode;
  28891. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  28892. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28893. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28894. }
  28895. else {
  28896. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28897. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28898. _this._generateMipMaps = false;
  28899. }
  28900. if (urls) {
  28901. _this.video.addEventListener("canplay", function () {
  28902. _this._createTexture();
  28903. });
  28904. urls.forEach(function (url) {
  28905. var source = document.createElement("source");
  28906. source.src = url;
  28907. _this.video.appendChild(source);
  28908. });
  28909. }
  28910. else {
  28911. _this._createTexture();
  28912. }
  28913. _this._lastUpdate = BABYLON.Tools.Now;
  28914. return _this;
  28915. }
  28916. VideoTexture.prototype._createTexture = function () {
  28917. var _this = this;
  28918. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  28919. if (this._autoLaunch) {
  28920. this._autoLaunch = false;
  28921. this.video.play();
  28922. }
  28923. this.video.addEventListener("playing", function () {
  28924. _this._texture.isReady = true;
  28925. });
  28926. };
  28927. VideoTexture.prototype.update = function () {
  28928. var now = BABYLON.Tools.Now;
  28929. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  28930. return false;
  28931. }
  28932. this._lastUpdate = now;
  28933. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  28934. return true;
  28935. };
  28936. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  28937. var video = document.createElement("video");
  28938. var constraintsDeviceId;
  28939. if (constraints && constraints.deviceId) {
  28940. constraintsDeviceId = {
  28941. exact: constraints.deviceId
  28942. };
  28943. }
  28944. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  28945. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  28946. if (navigator.getUserMedia) {
  28947. navigator.getUserMedia({
  28948. video: {
  28949. deviceId: constraintsDeviceId,
  28950. width: {
  28951. min: (constraints && constraints.minWidth) || 256,
  28952. max: (constraints && constraints.maxWidth) || 640
  28953. },
  28954. height: {
  28955. min: (constraints && constraints.minHeight) || 256,
  28956. max: (constraints && constraints.maxHeight) || 480
  28957. }
  28958. }
  28959. }, function (stream) {
  28960. if (video.mozSrcObject !== undefined) {
  28961. video.mozSrcObject = stream;
  28962. }
  28963. else {
  28964. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  28965. }
  28966. video.play();
  28967. if (onReady) {
  28968. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  28969. }
  28970. }, function (e) {
  28971. BABYLON.Tools.Error(e.name);
  28972. });
  28973. }
  28974. };
  28975. return VideoTexture;
  28976. }(BABYLON.Texture));
  28977. BABYLON.VideoTexture = VideoTexture;
  28978. })(BABYLON || (BABYLON = {}));
  28979. //# sourceMappingURL=babylon.videoTexture.js.map
  28980. /// <reference path="babylon.proceduralTexture.ts" />
  28981. var BABYLON;
  28982. (function (BABYLON) {
  28983. var CustomProceduralTexture = (function (_super) {
  28984. __extends(CustomProceduralTexture, _super);
  28985. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  28986. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  28987. _this._animate = true;
  28988. _this._time = 0;
  28989. _this._texturePath = texturePath;
  28990. //Try to load json
  28991. _this.loadJson(texturePath);
  28992. _this.refreshRate = 1;
  28993. return _this;
  28994. }
  28995. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  28996. var _this = this;
  28997. var that = this;
  28998. function noConfigFile() {
  28999. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  29000. try {
  29001. that.setFragment(that._texturePath);
  29002. }
  29003. catch (ex) {
  29004. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  29005. }
  29006. }
  29007. var configFileUrl = jsonUrl + "/config.json";
  29008. var xhr = new XMLHttpRequest();
  29009. xhr.open("GET", configFileUrl, true);
  29010. xhr.addEventListener("load", function () {
  29011. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  29012. try {
  29013. _this._config = JSON.parse(xhr.response);
  29014. _this.updateShaderUniforms();
  29015. _this.updateTextures();
  29016. _this.setFragment(_this._texturePath + "/custom");
  29017. _this._animate = _this._config.animate;
  29018. _this.refreshRate = _this._config.refreshrate;
  29019. }
  29020. catch (ex) {
  29021. noConfigFile();
  29022. }
  29023. }
  29024. else {
  29025. noConfigFile();
  29026. }
  29027. }, false);
  29028. xhr.addEventListener("error", function () {
  29029. noConfigFile();
  29030. }, false);
  29031. try {
  29032. xhr.send();
  29033. }
  29034. catch (ex) {
  29035. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  29036. }
  29037. };
  29038. CustomProceduralTexture.prototype.isReady = function () {
  29039. if (!_super.prototype.isReady.call(this)) {
  29040. return false;
  29041. }
  29042. for (var name in this._textures) {
  29043. var texture = this._textures[name];
  29044. if (!texture.isReady()) {
  29045. return false;
  29046. }
  29047. }
  29048. return true;
  29049. };
  29050. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  29051. if (this._animate) {
  29052. this._time += this.getScene().getAnimationRatio() * 0.03;
  29053. this.updateShaderUniforms();
  29054. }
  29055. _super.prototype.render.call(this, useCameraPostProcess);
  29056. };
  29057. CustomProceduralTexture.prototype.updateTextures = function () {
  29058. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  29059. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  29060. }
  29061. };
  29062. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  29063. if (this._config) {
  29064. for (var j = 0; j < this._config.uniforms.length; j++) {
  29065. var uniform = this._config.uniforms[j];
  29066. switch (uniform.type) {
  29067. case "float":
  29068. this.setFloat(uniform.name, uniform.value);
  29069. break;
  29070. case "color3":
  29071. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  29072. break;
  29073. case "color4":
  29074. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  29075. break;
  29076. case "vector2":
  29077. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  29078. break;
  29079. case "vector3":
  29080. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  29081. break;
  29082. }
  29083. }
  29084. }
  29085. this.setFloat("time", this._time);
  29086. };
  29087. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  29088. get: function () {
  29089. return this._animate;
  29090. },
  29091. set: function (value) {
  29092. this._animate = value;
  29093. },
  29094. enumerable: true,
  29095. configurable: true
  29096. });
  29097. return CustomProceduralTexture;
  29098. }(BABYLON.ProceduralTexture));
  29099. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  29100. })(BABYLON || (BABYLON = {}));
  29101. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  29102. var BABYLON;
  29103. (function (BABYLON) {
  29104. var EffectFallbacks = (function () {
  29105. function EffectFallbacks() {
  29106. this._defines = {};
  29107. this._currentRank = 32;
  29108. this._maxRank = -1;
  29109. }
  29110. EffectFallbacks.prototype.addFallback = function (rank, define) {
  29111. if (!this._defines[rank]) {
  29112. if (rank < this._currentRank) {
  29113. this._currentRank = rank;
  29114. }
  29115. if (rank > this._maxRank) {
  29116. this._maxRank = rank;
  29117. }
  29118. this._defines[rank] = new Array();
  29119. }
  29120. this._defines[rank].push(define);
  29121. };
  29122. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  29123. this._meshRank = rank;
  29124. this._mesh = mesh;
  29125. if (rank < this._currentRank) {
  29126. this._currentRank = rank;
  29127. }
  29128. if (rank > this._maxRank) {
  29129. this._maxRank = rank;
  29130. }
  29131. };
  29132. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  29133. get: function () {
  29134. return this._currentRank <= this._maxRank;
  29135. },
  29136. enumerable: true,
  29137. configurable: true
  29138. });
  29139. EffectFallbacks.prototype.reduce = function (currentDefines) {
  29140. // First we try to switch to CPU skinning
  29141. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  29142. this._mesh.computeBonesUsingShaders = false;
  29143. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  29144. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  29145. var scene = this._mesh.getScene();
  29146. for (var index = 0; index < scene.meshes.length; index++) {
  29147. var otherMesh = scene.meshes[index];
  29148. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  29149. otherMesh.computeBonesUsingShaders = false;
  29150. }
  29151. }
  29152. }
  29153. else {
  29154. var currentFallbacks = this._defines[this._currentRank];
  29155. if (currentFallbacks) {
  29156. for (var index = 0; index < currentFallbacks.length; index++) {
  29157. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  29158. }
  29159. }
  29160. this._currentRank++;
  29161. }
  29162. return currentDefines;
  29163. };
  29164. return EffectFallbacks;
  29165. }());
  29166. BABYLON.EffectFallbacks = EffectFallbacks;
  29167. var Effect = (function () {
  29168. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  29169. var _this = this;
  29170. this.uniqueId = 0;
  29171. this._isReady = false;
  29172. this._compilationError = "";
  29173. this._valueCache = {};
  29174. this._engine = engine;
  29175. this.name = baseName;
  29176. this.defines = defines;
  29177. this._uniformsNames = uniformsNames.concat(samplers);
  29178. this._samplers = samplers;
  29179. this._attributesNames = attributesNames;
  29180. this.onError = onError;
  29181. this.onCompiled = onCompiled;
  29182. this._indexParameters = indexParameters;
  29183. this.uniqueId = Effect._uniqueIdSeed++;
  29184. var vertexSource;
  29185. var fragmentSource;
  29186. if (baseName.vertexElement) {
  29187. vertexSource = document.getElementById(baseName.vertexElement);
  29188. if (!vertexSource) {
  29189. vertexSource = baseName.vertexElement;
  29190. }
  29191. }
  29192. else {
  29193. vertexSource = baseName.vertex || baseName;
  29194. }
  29195. if (baseName.fragmentElement) {
  29196. fragmentSource = document.getElementById(baseName.fragmentElement);
  29197. if (!fragmentSource) {
  29198. fragmentSource = baseName.fragmentElement;
  29199. }
  29200. }
  29201. else {
  29202. fragmentSource = baseName.fragment || baseName;
  29203. }
  29204. this._loadVertexShader(vertexSource, function (vertexCode) {
  29205. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  29206. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  29207. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  29208. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  29209. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  29210. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, attributesNames, defines, fallbacks);
  29211. });
  29212. });
  29213. });
  29214. });
  29215. });
  29216. });
  29217. }
  29218. Object.defineProperty(Effect.prototype, "key", {
  29219. get: function () {
  29220. return this._key;
  29221. },
  29222. enumerable: true,
  29223. configurable: true
  29224. });
  29225. // Properties
  29226. Effect.prototype.isReady = function () {
  29227. return this._isReady;
  29228. };
  29229. Effect.prototype.getProgram = function () {
  29230. return this._program;
  29231. };
  29232. Effect.prototype.getAttributesNames = function () {
  29233. return this._attributesNames;
  29234. };
  29235. Effect.prototype.getAttributeLocation = function (index) {
  29236. return this._attributes[index];
  29237. };
  29238. Effect.prototype.getAttributeLocationByName = function (name) {
  29239. var index = this._attributesNames.indexOf(name);
  29240. return this._attributes[index];
  29241. };
  29242. Effect.prototype.getAttributesCount = function () {
  29243. return this._attributes.length;
  29244. };
  29245. Effect.prototype.getUniformIndex = function (uniformName) {
  29246. return this._uniformsNames.indexOf(uniformName);
  29247. };
  29248. Effect.prototype.getUniform = function (uniformName) {
  29249. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  29250. };
  29251. Effect.prototype.getSamplers = function () {
  29252. return this._samplers;
  29253. };
  29254. Effect.prototype.getCompilationError = function () {
  29255. return this._compilationError;
  29256. };
  29257. Effect.prototype.getVertexShaderSource = function () {
  29258. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  29259. };
  29260. Effect.prototype.getFragmentShaderSource = function () {
  29261. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  29262. };
  29263. // Methods
  29264. Effect.prototype._loadVertexShader = function (vertex, callback) {
  29265. // DOM element ?
  29266. if (vertex instanceof HTMLElement) {
  29267. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  29268. callback(vertexCode);
  29269. return;
  29270. }
  29271. // Base64 encoded ?
  29272. if (vertex.substr(0, 7) === "base64:") {
  29273. var vertexBinary = window.atob(vertex.substr(7));
  29274. callback(vertexBinary);
  29275. return;
  29276. }
  29277. // Is in local store ?
  29278. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  29279. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  29280. return;
  29281. }
  29282. var vertexShaderUrl;
  29283. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  29284. vertexShaderUrl = vertex;
  29285. }
  29286. else {
  29287. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  29288. }
  29289. // Vertex shader
  29290. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  29291. };
  29292. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  29293. // DOM element ?
  29294. if (fragment instanceof HTMLElement) {
  29295. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  29296. callback(fragmentCode);
  29297. return;
  29298. }
  29299. // Base64 encoded ?
  29300. if (fragment.substr(0, 7) === "base64:") {
  29301. var fragmentBinary = window.atob(fragment.substr(7));
  29302. callback(fragmentBinary);
  29303. return;
  29304. }
  29305. // Is in local store ?
  29306. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  29307. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  29308. return;
  29309. }
  29310. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  29311. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  29312. return;
  29313. }
  29314. var fragmentShaderUrl;
  29315. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  29316. fragmentShaderUrl = fragment;
  29317. }
  29318. else {
  29319. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  29320. }
  29321. // Fragment shader
  29322. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  29323. };
  29324. Effect.prototype._dumpShadersName = function () {
  29325. if (this.name.vertexElement) {
  29326. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  29327. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  29328. }
  29329. else if (this.name.vertex) {
  29330. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  29331. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  29332. }
  29333. else {
  29334. BABYLON.Tools.Error("Vertex shader:" + this.name);
  29335. BABYLON.Tools.Error("Fragment shader:" + this.name);
  29336. }
  29337. };
  29338. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  29339. var preparedSourceCode = this._processPrecision(sourceCode);
  29340. if (this._engine.webGLVersion == 1) {
  29341. callback(preparedSourceCode);
  29342. return;
  29343. }
  29344. // Already converted
  29345. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  29346. callback(preparedSourceCode);
  29347. return;
  29348. }
  29349. // Remove extensions
  29350. // #extension GL_OES_standard_derivatives : enable
  29351. // #extension GL_EXT_shader_texture_lod : enable
  29352. // #extension GL_EXT_frag_depth : enable
  29353. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  29354. var result = preparedSourceCode.replace(regex, "");
  29355. // Migrate to GLSL v300
  29356. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  29357. result = result.replace(/attribute[ \t]/g, "in ");
  29358. result = result.replace(/[ \t]attribute/g, " in");
  29359. if (isFragment) {
  29360. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  29361. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  29362. result = result.replace(/texture2D\(/g, "texture(");
  29363. result = result.replace(/textureCube\(/g, "texture(");
  29364. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  29365. result = result.replace(/gl_FragColor/g, "glFragColor");
  29366. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  29367. }
  29368. callback(result);
  29369. };
  29370. Effect.prototype._processIncludes = function (sourceCode, callback) {
  29371. var _this = this;
  29372. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  29373. var match = regex.exec(sourceCode);
  29374. var returnValue = new String(sourceCode);
  29375. while (match != null) {
  29376. var includeFile = match[1];
  29377. if (Effect.IncludesShadersStore[includeFile]) {
  29378. // Substitution
  29379. var includeContent = Effect.IncludesShadersStore[includeFile];
  29380. if (match[2]) {
  29381. var splits = match[3].split(",");
  29382. for (var index = 0; index < splits.length; index += 2) {
  29383. var source = new RegExp(splits[index], "g");
  29384. var dest = splits[index + 1];
  29385. includeContent = includeContent.replace(source, dest);
  29386. }
  29387. }
  29388. if (match[4]) {
  29389. var indexString = match[5];
  29390. if (indexString.indexOf("..") !== -1) {
  29391. var indexSplits = indexString.split("..");
  29392. var minIndex = parseInt(indexSplits[0]);
  29393. var maxIndex = parseInt(indexSplits[1]);
  29394. var sourceIncludeContent = includeContent.slice(0);
  29395. includeContent = "";
  29396. if (isNaN(maxIndex)) {
  29397. maxIndex = this._indexParameters[indexSplits[1]];
  29398. }
  29399. for (var i = minIndex; i <= maxIndex; i++) {
  29400. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  29401. }
  29402. }
  29403. else {
  29404. includeContent = includeContent.replace(/\{X\}/g, indexString);
  29405. }
  29406. }
  29407. // Replace
  29408. returnValue = returnValue.replace(match[0], includeContent);
  29409. }
  29410. else {
  29411. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  29412. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  29413. Effect.IncludesShadersStore[includeFile] = fileContent;
  29414. _this._processIncludes(returnValue, callback);
  29415. });
  29416. return;
  29417. }
  29418. match = regex.exec(sourceCode);
  29419. }
  29420. callback(returnValue);
  29421. };
  29422. Effect.prototype._processPrecision = function (source) {
  29423. if (source.indexOf("precision highp float") === -1) {
  29424. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  29425. source = "precision mediump float;\n" + source;
  29426. }
  29427. else {
  29428. source = "precision highp float;\n" + source;
  29429. }
  29430. }
  29431. else {
  29432. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  29433. source = source.replace("precision highp float", "precision mediump float");
  29434. }
  29435. }
  29436. return source;
  29437. };
  29438. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  29439. try {
  29440. var engine = this._engine;
  29441. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  29442. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  29443. this._attributes = engine.getAttributes(this._program, attributesNames);
  29444. var index;
  29445. for (index = 0; index < this._samplers.length; index++) {
  29446. var sampler = this.getUniform(this._samplers[index]);
  29447. if (sampler == null) {
  29448. this._samplers.splice(index, 1);
  29449. index--;
  29450. }
  29451. }
  29452. engine.bindSamplers(this);
  29453. this._compilationError = "";
  29454. this._isReady = true;
  29455. if (this.onCompiled) {
  29456. this.onCompiled(this);
  29457. }
  29458. }
  29459. catch (e) {
  29460. this._compilationError = e.message;
  29461. // Let's go through fallbacks then
  29462. BABYLON.Tools.Error("Unable to compile effect: ");
  29463. BABYLON.Tools.Error("Defines: " + defines);
  29464. BABYLON.Tools.Error("Error: " + this._compilationError);
  29465. this._dumpShadersName();
  29466. if (fallbacks && fallbacks.isMoreFallbacks) {
  29467. BABYLON.Tools.Error("Trying next fallback.");
  29468. defines = fallbacks.reduce(defines);
  29469. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  29470. }
  29471. else {
  29472. if (this.onError) {
  29473. this.onError(this, this._compilationError);
  29474. }
  29475. }
  29476. }
  29477. };
  29478. Object.defineProperty(Effect.prototype, "isSupported", {
  29479. get: function () {
  29480. return this._compilationError === "";
  29481. },
  29482. enumerable: true,
  29483. configurable: true
  29484. });
  29485. Effect.prototype._bindTexture = function (channel, texture) {
  29486. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  29487. };
  29488. Effect.prototype.setTexture = function (channel, texture) {
  29489. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  29490. };
  29491. Effect.prototype.setTextureArray = function (channel, textures) {
  29492. if (this._samplers.indexOf(channel + "Ex") === -1) {
  29493. var initialPos = this._samplers.indexOf(channel);
  29494. for (var index = 1; index < textures.length; index++) {
  29495. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  29496. }
  29497. }
  29498. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  29499. };
  29500. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  29501. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  29502. };
  29503. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  29504. var changed = false;
  29505. var cache = this._valueCache[uniformName];
  29506. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  29507. changed = true;
  29508. cache = new BABYLON.Matrix();
  29509. }
  29510. var tm = cache.m;
  29511. var om = matrix.m;
  29512. for (var index = 0; index < 16; index++) {
  29513. if (tm[index] !== om[index]) {
  29514. tm[index] = om[index];
  29515. changed = true;
  29516. }
  29517. }
  29518. this._valueCache[uniformName] = cache;
  29519. return changed;
  29520. };
  29521. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  29522. var cache = this._valueCache[uniformName];
  29523. if (!cache) {
  29524. cache = [x, y];
  29525. this._valueCache[uniformName] = cache;
  29526. return true;
  29527. }
  29528. var changed = false;
  29529. if (cache[0] !== x) {
  29530. cache[0] = x;
  29531. changed = true;
  29532. }
  29533. if (cache[1] !== y) {
  29534. cache[1] = y;
  29535. changed = true;
  29536. }
  29537. return changed;
  29538. };
  29539. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  29540. var cache = this._valueCache[uniformName];
  29541. if (!cache) {
  29542. cache = [x, y, z];
  29543. this._valueCache[uniformName] = cache;
  29544. return true;
  29545. }
  29546. var changed = false;
  29547. if (cache[0] !== x) {
  29548. cache[0] = x;
  29549. changed = true;
  29550. }
  29551. if (cache[1] !== y) {
  29552. cache[1] = y;
  29553. changed = true;
  29554. }
  29555. if (cache[2] !== z) {
  29556. cache[2] = z;
  29557. changed = true;
  29558. }
  29559. return changed;
  29560. };
  29561. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  29562. var cache = this._valueCache[uniformName];
  29563. if (!cache) {
  29564. cache = [x, y, z, w];
  29565. this._valueCache[uniformName] = cache;
  29566. return true;
  29567. }
  29568. var changed = false;
  29569. if (cache[0] !== x) {
  29570. cache[0] = x;
  29571. changed = true;
  29572. }
  29573. if (cache[1] !== y) {
  29574. cache[1] = y;
  29575. changed = true;
  29576. }
  29577. if (cache[2] !== z) {
  29578. cache[2] = z;
  29579. changed = true;
  29580. }
  29581. if (cache[3] !== w) {
  29582. cache[3] = w;
  29583. changed = true;
  29584. }
  29585. return changed;
  29586. };
  29587. Effect.prototype.setIntArray = function (uniformName, array) {
  29588. this._valueCache[uniformName] = null;
  29589. this._engine.setIntArray(this.getUniform(uniformName), array);
  29590. return this;
  29591. };
  29592. Effect.prototype.setIntArray2 = function (uniformName, array) {
  29593. this._valueCache[uniformName] = null;
  29594. this._engine.setIntArray2(this.getUniform(uniformName), array);
  29595. return this;
  29596. };
  29597. Effect.prototype.setIntArray3 = function (uniformName, array) {
  29598. this._valueCache[uniformName] = null;
  29599. this._engine.setIntArray3(this.getUniform(uniformName), array);
  29600. return this;
  29601. };
  29602. Effect.prototype.setIntArray4 = function (uniformName, array) {
  29603. this._valueCache[uniformName] = null;
  29604. this._engine.setIntArray4(this.getUniform(uniformName), array);
  29605. return this;
  29606. };
  29607. Effect.prototype.setFloatArray = function (uniformName, array) {
  29608. this._valueCache[uniformName] = null;
  29609. this._engine.setFloatArray(this.getUniform(uniformName), array);
  29610. return this;
  29611. };
  29612. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  29613. this._valueCache[uniformName] = null;
  29614. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  29615. return this;
  29616. };
  29617. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  29618. this._valueCache[uniformName] = null;
  29619. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  29620. return this;
  29621. };
  29622. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  29623. this._valueCache[uniformName] = null;
  29624. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  29625. return this;
  29626. };
  29627. Effect.prototype.setArray = function (uniformName, array) {
  29628. this._valueCache[uniformName] = null;
  29629. this._engine.setArray(this.getUniform(uniformName), array);
  29630. return this;
  29631. };
  29632. Effect.prototype.setArray2 = function (uniformName, array) {
  29633. this._valueCache[uniformName] = null;
  29634. this._engine.setArray2(this.getUniform(uniformName), array);
  29635. return this;
  29636. };
  29637. Effect.prototype.setArray3 = function (uniformName, array) {
  29638. this._valueCache[uniformName] = null;
  29639. this._engine.setArray3(this.getUniform(uniformName), array);
  29640. return this;
  29641. };
  29642. Effect.prototype.setArray4 = function (uniformName, array) {
  29643. this._valueCache[uniformName] = null;
  29644. this._engine.setArray4(this.getUniform(uniformName), array);
  29645. return this;
  29646. };
  29647. Effect.prototype.setMatrices = function (uniformName, matrices) {
  29648. this._valueCache[uniformName] = null;
  29649. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  29650. return this;
  29651. };
  29652. Effect.prototype.setMatrix = function (uniformName, matrix) {
  29653. if (this._cacheMatrix(uniformName, matrix)) {
  29654. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  29655. }
  29656. return this;
  29657. };
  29658. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  29659. this._valueCache[uniformName] = null;
  29660. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  29661. return this;
  29662. };
  29663. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  29664. this._valueCache[uniformName] = null;
  29665. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  29666. return this;
  29667. };
  29668. Effect.prototype.setFloat = function (uniformName, value) {
  29669. var cache = this._valueCache[uniformName];
  29670. if (cache !== undefined && cache === value)
  29671. return this;
  29672. this._valueCache[uniformName] = value;
  29673. this._engine.setFloat(this.getUniform(uniformName), value);
  29674. return this;
  29675. };
  29676. Effect.prototype.setBool = function (uniformName, bool) {
  29677. var cache = this._valueCache[uniformName];
  29678. if (cache !== undefined && cache === bool)
  29679. return this;
  29680. this._valueCache[uniformName] = bool;
  29681. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  29682. return this;
  29683. };
  29684. Effect.prototype.setVector2 = function (uniformName, vector2) {
  29685. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  29686. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  29687. }
  29688. return this;
  29689. };
  29690. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  29691. if (this._cacheFloat2(uniformName, x, y)) {
  29692. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  29693. }
  29694. return this;
  29695. };
  29696. Effect.prototype.setVector3 = function (uniformName, vector3) {
  29697. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  29698. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  29699. }
  29700. return this;
  29701. };
  29702. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  29703. if (this._cacheFloat3(uniformName, x, y, z)) {
  29704. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  29705. }
  29706. return this;
  29707. };
  29708. Effect.prototype.setVector4 = function (uniformName, vector4) {
  29709. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  29710. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  29711. }
  29712. return this;
  29713. };
  29714. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  29715. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  29716. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  29717. }
  29718. return this;
  29719. };
  29720. Effect.prototype.setColor3 = function (uniformName, color3) {
  29721. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  29722. this._engine.setColor3(this.getUniform(uniformName), color3);
  29723. }
  29724. return this;
  29725. };
  29726. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  29727. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  29728. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  29729. }
  29730. return this;
  29731. };
  29732. Effect.prototype._recombineShader = function (node) {
  29733. if (node.define) {
  29734. if (node.condition) {
  29735. var defineIndex = this.defines.indexOf("#define " + node.define);
  29736. if (defineIndex === -1) {
  29737. return null;
  29738. }
  29739. var nextComma = this.defines.indexOf("\n", defineIndex);
  29740. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  29741. var condition = defineValue + node.condition;
  29742. if (!eval(condition)) {
  29743. return null;
  29744. }
  29745. }
  29746. else if (node.ndef) {
  29747. if (this.defines.indexOf("#define " + node.define) !== -1) {
  29748. return null;
  29749. }
  29750. }
  29751. else if (this.defines.indexOf("#define " + node.define) === -1) {
  29752. return null;
  29753. }
  29754. }
  29755. var result = "";
  29756. for (var index = 0; index < node.children.length; index++) {
  29757. var line = node.children[index];
  29758. if (line.children) {
  29759. var combined = this._recombineShader(line);
  29760. if (combined !== null) {
  29761. result += combined + "\r\n";
  29762. }
  29763. continue;
  29764. }
  29765. if (line.length > 0) {
  29766. result += line + "\r\n";
  29767. }
  29768. }
  29769. return result;
  29770. };
  29771. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  29772. var root = {
  29773. children: []
  29774. };
  29775. var currentNode = root;
  29776. var lines = shaderString.split("\n");
  29777. for (var index = 0; index < lines.length; index++) {
  29778. var line = lines[index].trim();
  29779. // #ifdef
  29780. var pos = line.indexOf("#ifdef ");
  29781. if (pos !== -1) {
  29782. var define = line.substr(pos + 7);
  29783. var newNode = {
  29784. condition: null,
  29785. ndef: false,
  29786. define: define,
  29787. children: [],
  29788. parent: currentNode
  29789. };
  29790. currentNode.children.push(newNode);
  29791. currentNode = newNode;
  29792. continue;
  29793. }
  29794. // #ifndef
  29795. var pos = line.indexOf("#ifndef ");
  29796. if (pos !== -1) {
  29797. var define = line.substr(pos + 8);
  29798. newNode = {
  29799. condition: null,
  29800. define: define,
  29801. ndef: true,
  29802. children: [],
  29803. parent: currentNode
  29804. };
  29805. currentNode.children.push(newNode);
  29806. currentNode = newNode;
  29807. continue;
  29808. }
  29809. // #if
  29810. var pos = line.indexOf("#if ");
  29811. if (pos !== -1) {
  29812. var define = line.substr(pos + 4).trim();
  29813. var conditionPos = define.indexOf(" ");
  29814. newNode = {
  29815. condition: define.substr(conditionPos + 1),
  29816. define: define.substr(0, conditionPos),
  29817. ndef: false,
  29818. children: [],
  29819. parent: currentNode
  29820. };
  29821. currentNode.children.push(newNode);
  29822. currentNode = newNode;
  29823. continue;
  29824. }
  29825. // #endif
  29826. pos = line.indexOf("#endif");
  29827. if (pos !== -1) {
  29828. currentNode = currentNode.parent;
  29829. continue;
  29830. }
  29831. currentNode.children.push(line);
  29832. }
  29833. // Recombine
  29834. return this._recombineShader(root);
  29835. };
  29836. return Effect;
  29837. }());
  29838. Effect._uniqueIdSeed = 0;
  29839. // Statics
  29840. Effect.ShadersStore = {};
  29841. Effect.IncludesShadersStore = {};
  29842. BABYLON.Effect = Effect;
  29843. })(BABYLON || (BABYLON = {}));
  29844. //# sourceMappingURL=babylon.effect.js.map
  29845. var BABYLON;
  29846. (function (BABYLON) {
  29847. var MaterialHelper = (function () {
  29848. function MaterialHelper() {
  29849. }
  29850. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useInstances) {
  29851. if (!defines._areAttributesDirty) {
  29852. return;
  29853. }
  29854. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  29855. if (defines._needUVs) {
  29856. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  29857. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  29858. }
  29859. else {
  29860. defines["UV1"] = false;
  29861. defines["UV2"] = false;
  29862. }
  29863. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  29864. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  29865. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29866. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  29867. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  29868. }
  29869. else {
  29870. defines["NUM_BONE_INFLUENCERS"] = 0;
  29871. defines["BonesPerMesh"] = 0;
  29872. }
  29873. };
  29874. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights, disableLighting) {
  29875. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29876. if (disableLighting === void 0) { disableLighting = false; }
  29877. if (!defines._areLightsDirty) {
  29878. return defines._needNormals;
  29879. }
  29880. var lightIndex = 0;
  29881. var needNormals = false;
  29882. var needRebuild = false;
  29883. var lightmapMode = false;
  29884. var shadowEnabled = false;
  29885. var specularEnabled = false;
  29886. if (scene.lightsEnabled && !disableLighting) {
  29887. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  29888. var light = _a[_i];
  29889. needNormals = true;
  29890. if (defines["LIGHT" + lightIndex] === undefined) {
  29891. needRebuild = true;
  29892. }
  29893. defines["LIGHT" + lightIndex] = true;
  29894. defines["SPOTLIGHT" + lightIndex] = false;
  29895. defines["HEMILIGHT" + lightIndex] = false;
  29896. defines["POINTLIGHT" + lightIndex] = false;
  29897. defines["DIRLIGHT" + lightIndex] = false;
  29898. var type;
  29899. if (light instanceof BABYLON.SpotLight) {
  29900. type = "SPOTLIGHT" + lightIndex;
  29901. }
  29902. else if (light instanceof BABYLON.HemisphericLight) {
  29903. type = "HEMILIGHT" + lightIndex;
  29904. }
  29905. else if (light instanceof BABYLON.PointLight) {
  29906. type = "POINTLIGHT" + lightIndex;
  29907. }
  29908. else {
  29909. type = "DIRLIGHT" + lightIndex;
  29910. }
  29911. defines[type] = true;
  29912. // Specular
  29913. if (!light.specular.equalsFloats(0, 0, 0)) {
  29914. specularEnabled = true;
  29915. }
  29916. // Shadows
  29917. defines["SHADOW" + lightIndex] = false;
  29918. if (scene.shadowsEnabled) {
  29919. var shadowGenerator = light.getShadowGenerator();
  29920. if (mesh && mesh.receiveShadows && shadowGenerator) {
  29921. defines["SHADOW" + lightIndex] = true;
  29922. shadowEnabled = true;
  29923. defines["SHADOWPCF" + lightIndex] = false;
  29924. defines["SHADOWESM" + lightIndex] = false;
  29925. if (shadowGenerator.usePoissonSampling) {
  29926. defines["SHADOWPCF" + lightIndex] = true;
  29927. }
  29928. else if (shadowGenerator.useExponentialShadowMap || shadowGenerator.useBlurExponentialShadowMap) {
  29929. defines["SHADOWESM" + lightIndex] = true;
  29930. }
  29931. }
  29932. }
  29933. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  29934. lightmapMode = true;
  29935. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  29936. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  29937. }
  29938. else {
  29939. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  29940. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  29941. }
  29942. lightIndex++;
  29943. if (lightIndex === maxSimultaneousLights)
  29944. break;
  29945. }
  29946. }
  29947. defines["SPECULARTERM"] = specularEnabled;
  29948. defines["SHADOWS"] = shadowEnabled;
  29949. // Resetting all other lights if any
  29950. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  29951. if (defines["LIGHT" + index] !== undefined) {
  29952. defines["LIGHT" + index] = false;
  29953. }
  29954. }
  29955. var caps = scene.getEngine().getCaps();
  29956. if (defines["SHADOWFULLFLOAT"] === undefined) {
  29957. needRebuild = true;
  29958. }
  29959. defines["SHADOWFULLFLOAT"] = (shadowEnabled && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender);
  29960. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  29961. if (needRebuild) {
  29962. defines.rebuild();
  29963. }
  29964. return needNormals;
  29965. };
  29966. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  29967. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29968. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  29969. if (!defines["LIGHT" + lightIndex]) {
  29970. break;
  29971. }
  29972. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  29973. samplersList.push("shadowSampler" + lightIndex);
  29974. }
  29975. };
  29976. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  29977. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29978. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  29979. if (!defines["LIGHT" + lightIndex]) {
  29980. break;
  29981. }
  29982. if (lightIndex > 0) {
  29983. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  29984. }
  29985. if (defines["SHADOW" + lightIndex]) {
  29986. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  29987. }
  29988. if (defines["SHADOWPCF" + lightIndex]) {
  29989. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  29990. }
  29991. if (defines["SHADOWESM" + lightIndex]) {
  29992. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  29993. }
  29994. }
  29995. };
  29996. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  29997. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  29998. fallbacks.addCPUSkinningFallback(0, mesh);
  29999. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30000. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30001. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  30002. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  30003. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  30004. }
  30005. }
  30006. };
  30007. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  30008. if (defines["INSTANCES"]) {
  30009. attribs.push("world0");
  30010. attribs.push("world1");
  30011. attribs.push("world2");
  30012. attribs.push("world3");
  30013. }
  30014. };
  30015. // Bindings
  30016. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  30017. var shadowGenerator = light.getShadowGenerator();
  30018. if (mesh.receiveShadows && shadowGenerator) {
  30019. if (!light.needCube()) {
  30020. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  30021. }
  30022. else {
  30023. if (!depthValuesAlreadySet) {
  30024. depthValuesAlreadySet = true;
  30025. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  30026. }
  30027. }
  30028. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  30029. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.depthScale);
  30030. }
  30031. return depthValuesAlreadySet;
  30032. };
  30033. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  30034. if (light instanceof BABYLON.PointLight) {
  30035. // Point Light
  30036. light.transferToEffect(effect, "vLightData" + lightIndex);
  30037. }
  30038. else if (light instanceof BABYLON.DirectionalLight) {
  30039. // Directional Light
  30040. light.transferToEffect(effect, "vLightData" + lightIndex);
  30041. }
  30042. else if (light instanceof BABYLON.SpotLight) {
  30043. // Spot Light
  30044. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  30045. }
  30046. else if (light instanceof BABYLON.HemisphericLight) {
  30047. // Hemispheric Light
  30048. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  30049. }
  30050. };
  30051. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  30052. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  30053. var lightIndex = 0;
  30054. var depthValuesAlreadySet = false;
  30055. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  30056. var light = _a[_i];
  30057. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  30058. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  30059. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  30060. if (defines["SPECULARTERM"]) {
  30061. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  30062. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  30063. }
  30064. // Shadows
  30065. if (scene.shadowsEnabled) {
  30066. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  30067. }
  30068. lightIndex++;
  30069. if (lightIndex === maxSimultaneousLights)
  30070. break;
  30071. }
  30072. };
  30073. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  30074. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  30075. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  30076. effect.setColor3("vFogColor", scene.fogColor);
  30077. }
  30078. };
  30079. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  30080. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30081. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  30082. if (matrices) {
  30083. effect.setMatrices("mBones", matrices);
  30084. }
  30085. }
  30086. };
  30087. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  30088. if (defines["LOGARITHMICDEPTH"]) {
  30089. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  30090. }
  30091. };
  30092. MaterialHelper.BindClipPlane = function (effect, scene) {
  30093. if (scene.clipPlane) {
  30094. var clipPlane = scene.clipPlane;
  30095. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  30096. }
  30097. };
  30098. return MaterialHelper;
  30099. }());
  30100. BABYLON.MaterialHelper = MaterialHelper;
  30101. })(BABYLON || (BABYLON = {}));
  30102. //# sourceMappingURL=babylon.materialHelper.js.map
  30103. var BABYLON;
  30104. (function (BABYLON) {
  30105. var FresnelParameters = (function () {
  30106. function FresnelParameters() {
  30107. this._isEnabled = true;
  30108. this.leftColor = BABYLON.Color3.White();
  30109. this.rightColor = BABYLON.Color3.Black();
  30110. this.bias = 0;
  30111. this.power = 1;
  30112. }
  30113. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  30114. get: function () {
  30115. return this._isEnabled;
  30116. },
  30117. set: function (value) {
  30118. if (this._isEnabled === value) {
  30119. return;
  30120. }
  30121. this._isEnabled = value;
  30122. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  30123. },
  30124. enumerable: true,
  30125. configurable: true
  30126. });
  30127. FresnelParameters.prototype.clone = function () {
  30128. var newFresnelParameters = new FresnelParameters();
  30129. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  30130. return newFresnelParameters;
  30131. };
  30132. FresnelParameters.prototype.serialize = function () {
  30133. var serializationObject = {};
  30134. serializationObject.isEnabled = this.isEnabled;
  30135. serializationObject.leftColor = this.leftColor;
  30136. serializationObject.rightColor = this.rightColor;
  30137. serializationObject.bias = this.bias;
  30138. serializationObject.power = this.power;
  30139. return serializationObject;
  30140. };
  30141. FresnelParameters.Parse = function (parsedFresnelParameters) {
  30142. var fresnelParameters = new FresnelParameters();
  30143. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  30144. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  30145. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  30146. fresnelParameters.bias = parsedFresnelParameters.bias;
  30147. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  30148. return fresnelParameters;
  30149. };
  30150. return FresnelParameters;
  30151. }());
  30152. BABYLON.FresnelParameters = FresnelParameters;
  30153. })(BABYLON || (BABYLON = {}));
  30154. //# sourceMappingURL=babylon.fresnelParameters.js.map
  30155. var BABYLON;
  30156. (function (BABYLON) {
  30157. var MaterialDefines = (function () {
  30158. function MaterialDefines(trackIsDirty) {
  30159. this._isDirty = true;
  30160. this._trackIsDirty = false;
  30161. this._areLightsDirty = true;
  30162. this._areAttributesDirty = true;
  30163. this._areTexturesDirty = true;
  30164. this._areFresnelDirty = true;
  30165. this._areMiscDirty = true;
  30166. this._needNormals = false;
  30167. this._needUVs = false;
  30168. this._trackIsDirty = trackIsDirty;
  30169. }
  30170. MaterialDefines.prototype._reBind = function (key) {
  30171. this["_" + key] = this[key];
  30172. Object.defineProperty(this, key, {
  30173. get: function () {
  30174. return this["_" + key];
  30175. },
  30176. set: function (value) {
  30177. if (this["_" + key] === value) {
  30178. return;
  30179. }
  30180. this["_" + key] = value;
  30181. this._isDirty = true;
  30182. },
  30183. enumerable: true,
  30184. configurable: true
  30185. });
  30186. };
  30187. MaterialDefines.prototype.rebuild = function () {
  30188. if (this._keys) {
  30189. delete this._keys;
  30190. }
  30191. this._keys = [];
  30192. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30193. var key = _a[_i];
  30194. if (key[0] === "_") {
  30195. continue;
  30196. }
  30197. this._keys.push(key);
  30198. if (!this._trackIsDirty) {
  30199. continue;
  30200. }
  30201. if (Object.getOwnPropertyDescriptor(this, key).get) {
  30202. continue;
  30203. }
  30204. this._reBind(key);
  30205. }
  30206. this._isDirty = true;
  30207. };
  30208. MaterialDefines.prototype.isEqual = function (other) {
  30209. if (this._keys.length !== other._keys.length) {
  30210. return false;
  30211. }
  30212. for (var index = 0; index < this._keys.length; index++) {
  30213. var prop = this._keys[index];
  30214. if (this[prop] !== other[prop]) {
  30215. return false;
  30216. }
  30217. }
  30218. return true;
  30219. };
  30220. MaterialDefines.prototype.cloneTo = function (other) {
  30221. if (this._keys.length !== other._keys.length) {
  30222. other._keys = this._keys.slice(0);
  30223. }
  30224. for (var index = 0; index < this._keys.length; index++) {
  30225. var prop = this._keys[index];
  30226. other[prop] = this[prop];
  30227. }
  30228. };
  30229. MaterialDefines.prototype.reset = function () {
  30230. for (var index = 0; index < this._keys.length; index++) {
  30231. var prop = this._keys[index];
  30232. if (typeof (this[prop]) === "number") {
  30233. this[prop] = 0;
  30234. }
  30235. else {
  30236. this[prop] = false;
  30237. }
  30238. }
  30239. };
  30240. MaterialDefines.prototype.toString = function () {
  30241. var result = "";
  30242. for (var index = 0; index < this._keys.length; index++) {
  30243. var prop = this._keys[index];
  30244. var value = this[prop];
  30245. if (typeof (value) === "number") {
  30246. result += "#define " + prop + " " + this[prop] + "\n";
  30247. }
  30248. else if (value) {
  30249. result += "#define " + prop + "\n";
  30250. }
  30251. }
  30252. return result;
  30253. };
  30254. return MaterialDefines;
  30255. }());
  30256. BABYLON.MaterialDefines = MaterialDefines;
  30257. var Material = (function () {
  30258. function Material(name, scene, doNotAdd) {
  30259. this.checkReadyOnEveryCall = false;
  30260. this.checkReadyOnlyOnce = false;
  30261. this.state = "";
  30262. this.alpha = 1.0;
  30263. this._backFaceCulling = true;
  30264. this.doNotSerialize = false;
  30265. this.storeEffectOnSubMeshes = false;
  30266. /**
  30267. * An event triggered when the material is disposed.
  30268. * @type {BABYLON.Observable}
  30269. */
  30270. this.onDisposeObservable = new BABYLON.Observable();
  30271. /**
  30272. * An event triggered when the material is bound.
  30273. * @type {BABYLON.Observable}
  30274. */
  30275. this.onBindObservable = new BABYLON.Observable();
  30276. /**
  30277. * An event triggered when the material is unbound.
  30278. * @type {BABYLON.Observable}
  30279. */
  30280. this.onUnBindObservable = new BABYLON.Observable();
  30281. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30282. this.disableDepthWrite = false;
  30283. this._fogEnabled = true;
  30284. this.pointSize = 1.0;
  30285. this.zOffset = 0;
  30286. this._wasPreviouslyReady = false;
  30287. this._fillMode = Material.TriangleFillMode;
  30288. this.name = name;
  30289. this.id = name;
  30290. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30291. if (this._scene.useRightHandedSystem) {
  30292. this.sideOrientation = Material.ClockWiseSideOrientation;
  30293. }
  30294. else {
  30295. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30296. }
  30297. if (!doNotAdd) {
  30298. this._scene.materials.push(this);
  30299. }
  30300. }
  30301. Object.defineProperty(Material, "TriangleFillMode", {
  30302. get: function () {
  30303. return Material._TriangleFillMode;
  30304. },
  30305. enumerable: true,
  30306. configurable: true
  30307. });
  30308. Object.defineProperty(Material, "WireFrameFillMode", {
  30309. get: function () {
  30310. return Material._WireFrameFillMode;
  30311. },
  30312. enumerable: true,
  30313. configurable: true
  30314. });
  30315. Object.defineProperty(Material, "PointFillMode", {
  30316. get: function () {
  30317. return Material._PointFillMode;
  30318. },
  30319. enumerable: true,
  30320. configurable: true
  30321. });
  30322. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30323. get: function () {
  30324. return Material._ClockWiseSideOrientation;
  30325. },
  30326. enumerable: true,
  30327. configurable: true
  30328. });
  30329. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30330. get: function () {
  30331. return Material._CounterClockWiseSideOrientation;
  30332. },
  30333. enumerable: true,
  30334. configurable: true
  30335. });
  30336. Object.defineProperty(Material, "TextureDirtyFlag", {
  30337. get: function () {
  30338. return Material._TextureDirtyFlag;
  30339. },
  30340. enumerable: true,
  30341. configurable: true
  30342. });
  30343. Object.defineProperty(Material, "LightDirtyFlag", {
  30344. get: function () {
  30345. return Material._LightDirtyFlag;
  30346. },
  30347. enumerable: true,
  30348. configurable: true
  30349. });
  30350. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30351. get: function () {
  30352. return Material._FresnelDirtyFlag;
  30353. },
  30354. enumerable: true,
  30355. configurable: true
  30356. });
  30357. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30358. get: function () {
  30359. return Material._AttributesDirtyFlag;
  30360. },
  30361. enumerable: true,
  30362. configurable: true
  30363. });
  30364. Object.defineProperty(Material, "MiscDirtyFlag", {
  30365. get: function () {
  30366. return Material._MiscDirtyFlag;
  30367. },
  30368. enumerable: true,
  30369. configurable: true
  30370. });
  30371. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30372. get: function () {
  30373. return this._backFaceCulling;
  30374. },
  30375. set: function (value) {
  30376. if (this._backFaceCulling === value) {
  30377. return;
  30378. }
  30379. this._backFaceCulling = value;
  30380. this.markAsDirty(Material.TextureDirtyFlag);
  30381. },
  30382. enumerable: true,
  30383. configurable: true
  30384. });
  30385. Object.defineProperty(Material.prototype, "onDispose", {
  30386. set: function (callback) {
  30387. if (this._onDisposeObserver) {
  30388. this.onDisposeObservable.remove(this._onDisposeObserver);
  30389. }
  30390. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30391. },
  30392. enumerable: true,
  30393. configurable: true
  30394. });
  30395. Object.defineProperty(Material.prototype, "onBind", {
  30396. set: function (callback) {
  30397. if (this._onBindObserver) {
  30398. this.onBindObservable.remove(this._onBindObserver);
  30399. }
  30400. this._onBindObserver = this.onBindObservable.add(callback);
  30401. },
  30402. enumerable: true,
  30403. configurable: true
  30404. });
  30405. Object.defineProperty(Material.prototype, "fogEnabled", {
  30406. get: function () {
  30407. return this._fogEnabled;
  30408. },
  30409. set: function (value) {
  30410. if (this._fogEnabled === value) {
  30411. return;
  30412. }
  30413. this._fogEnabled = value;
  30414. this.markAsDirty(Material.MiscDirtyFlag);
  30415. },
  30416. enumerable: true,
  30417. configurable: true
  30418. });
  30419. Object.defineProperty(Material.prototype, "wireframe", {
  30420. get: function () {
  30421. return this._fillMode === Material.WireFrameFillMode;
  30422. },
  30423. set: function (value) {
  30424. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  30425. },
  30426. enumerable: true,
  30427. configurable: true
  30428. });
  30429. Object.defineProperty(Material.prototype, "pointsCloud", {
  30430. get: function () {
  30431. return this._fillMode === Material.PointFillMode;
  30432. },
  30433. set: function (value) {
  30434. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  30435. },
  30436. enumerable: true,
  30437. configurable: true
  30438. });
  30439. Object.defineProperty(Material.prototype, "fillMode", {
  30440. get: function () {
  30441. return this._fillMode;
  30442. },
  30443. set: function (value) {
  30444. if (this._fillMode === value) {
  30445. return;
  30446. }
  30447. this._fillMode = value;
  30448. this.markAsDirty(Material.MiscDirtyFlag);
  30449. },
  30450. enumerable: true,
  30451. configurable: true
  30452. });
  30453. /**
  30454. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30455. * subclasses should override adding information pertainent to themselves
  30456. */
  30457. Material.prototype.toString = function (fullDetails) {
  30458. var ret = "Name: " + this.name;
  30459. if (fullDetails) {
  30460. }
  30461. return ret;
  30462. };
  30463. /**
  30464. * Child classes can use it to update shaders
  30465. */
  30466. Material.prototype.markAsDirty = function (flag) {
  30467. };
  30468. Material.prototype.getClassName = function () {
  30469. return "Material";
  30470. };
  30471. Object.defineProperty(Material.prototype, "isFrozen", {
  30472. get: function () {
  30473. return this.checkReadyOnlyOnce;
  30474. },
  30475. enumerable: true,
  30476. configurable: true
  30477. });
  30478. Material.prototype.freeze = function () {
  30479. this.checkReadyOnlyOnce = true;
  30480. };
  30481. Material.prototype.unfreeze = function () {
  30482. this.checkReadyOnlyOnce = false;
  30483. };
  30484. Material.prototype.isReady = function (mesh, useInstances) {
  30485. return true;
  30486. };
  30487. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30488. return false;
  30489. };
  30490. Material.prototype.getEffect = function () {
  30491. return this._effect;
  30492. };
  30493. Material.prototype.getScene = function () {
  30494. return this._scene;
  30495. };
  30496. Material.prototype.needAlphaBlending = function () {
  30497. return (this.alpha < 1.0);
  30498. };
  30499. Material.prototype.needAlphaTesting = function () {
  30500. return false;
  30501. };
  30502. Material.prototype.getAlphaTestTexture = function () {
  30503. return null;
  30504. };
  30505. Material.prototype.markDirty = function () {
  30506. this._wasPreviouslyReady = false;
  30507. };
  30508. Material.prototype._preBind = function (effect) {
  30509. var engine = this._scene.getEngine();
  30510. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  30511. engine.enableEffect(effect ? effect : this._effect);
  30512. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  30513. };
  30514. Material.prototype.bind = function (world, mesh) {
  30515. };
  30516. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30517. };
  30518. Material.prototype.bindOnlyWorldMatrix = function (world) {
  30519. };
  30520. Material.prototype._afterBind = function (mesh) {
  30521. this._scene._cachedMaterial = this;
  30522. this.onBindObservable.notifyObservers(mesh);
  30523. if (this.disableDepthWrite) {
  30524. var engine = this._scene.getEngine();
  30525. this._cachedDepthWriteState = engine.getDepthWrite();
  30526. engine.setDepthWrite(false);
  30527. }
  30528. };
  30529. Material.prototype.unbind = function () {
  30530. this.onUnBindObservable.notifyObservers(this);
  30531. if (this.disableDepthWrite) {
  30532. var engine = this._scene.getEngine();
  30533. engine.setDepthWrite(this._cachedDepthWriteState);
  30534. }
  30535. };
  30536. Material.prototype.clone = function (name) {
  30537. return null;
  30538. };
  30539. Material.prototype.getBindedMeshes = function () {
  30540. var result = new Array();
  30541. for (var index = 0; index < this._scene.meshes.length; index++) {
  30542. var mesh = this._scene.meshes[index];
  30543. if (mesh.material === this) {
  30544. result.push(mesh);
  30545. }
  30546. }
  30547. return result;
  30548. };
  30549. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30550. // Animations
  30551. this.getScene().stopAnimation(this);
  30552. // Remove from scene
  30553. var index = this._scene.materials.indexOf(this);
  30554. if (index >= 0) {
  30555. this._scene.materials.splice(index, 1);
  30556. }
  30557. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  30558. if (forceDisposeEffect && this._effect) {
  30559. this._scene.getEngine()._releaseEffect(this._effect);
  30560. this._effect = null;
  30561. }
  30562. // Remove from meshes
  30563. for (index = 0; index < this._scene.meshes.length; index++) {
  30564. var mesh = this._scene.meshes[index];
  30565. if (mesh.material === this) {
  30566. mesh.material = null;
  30567. }
  30568. }
  30569. // Callback
  30570. this.onDisposeObservable.notifyObservers(this);
  30571. this.onDisposeObservable.clear();
  30572. this.onBindObservable.clear();
  30573. this.onUnBindObservable.clear();
  30574. };
  30575. Material.prototype.serialize = function () {
  30576. return BABYLON.SerializationHelper.Serialize(this);
  30577. };
  30578. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  30579. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  30580. multiMaterial.id = parsedMultiMaterial.id;
  30581. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  30582. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  30583. var subMatId = parsedMultiMaterial.materials[matIndex];
  30584. if (subMatId) {
  30585. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  30586. }
  30587. else {
  30588. multiMaterial.subMaterials.push(null);
  30589. }
  30590. }
  30591. return multiMaterial;
  30592. };
  30593. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  30594. if (!parsedMaterial.customType) {
  30595. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  30596. }
  30597. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  30598. return materialType.Parse(parsedMaterial, scene, rootUrl);
  30599. ;
  30600. };
  30601. return Material;
  30602. }());
  30603. Material._TriangleFillMode = 0;
  30604. Material._WireFrameFillMode = 1;
  30605. Material._PointFillMode = 2;
  30606. Material._ClockWiseSideOrientation = 0;
  30607. Material._CounterClockWiseSideOrientation = 1;
  30608. Material._TextureDirtyFlag = 0;
  30609. Material._LightDirtyFlag = 1;
  30610. Material._FresnelDirtyFlag = 2;
  30611. Material._AttributesDirtyFlag = 4;
  30612. Material._MiscDirtyFlag = 8;
  30613. __decorate([
  30614. BABYLON.serialize()
  30615. ], Material.prototype, "id", void 0);
  30616. __decorate([
  30617. BABYLON.serialize()
  30618. ], Material.prototype, "name", void 0);
  30619. __decorate([
  30620. BABYLON.serialize()
  30621. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  30622. __decorate([
  30623. BABYLON.serialize()
  30624. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  30625. __decorate([
  30626. BABYLON.serialize()
  30627. ], Material.prototype, "state", void 0);
  30628. __decorate([
  30629. BABYLON.serialize()
  30630. ], Material.prototype, "alpha", void 0);
  30631. __decorate([
  30632. BABYLON.serialize("backFaceCulling")
  30633. ], Material.prototype, "_backFaceCulling", void 0);
  30634. __decorate([
  30635. BABYLON.serialize()
  30636. ], Material.prototype, "sideOrientation", void 0);
  30637. __decorate([
  30638. BABYLON.serialize()
  30639. ], Material.prototype, "alphaMode", void 0);
  30640. __decorate([
  30641. BABYLON.serialize()
  30642. ], Material.prototype, "disableDepthWrite", void 0);
  30643. __decorate([
  30644. BABYLON.serialize("fogEnabled")
  30645. ], Material.prototype, "_fogEnabled", void 0);
  30646. __decorate([
  30647. BABYLON.serialize()
  30648. ], Material.prototype, "pointSize", void 0);
  30649. __decorate([
  30650. BABYLON.serialize()
  30651. ], Material.prototype, "zOffset", void 0);
  30652. __decorate([
  30653. BABYLON.serialize()
  30654. ], Material.prototype, "wireframe", null);
  30655. __decorate([
  30656. BABYLON.serialize()
  30657. ], Material.prototype, "pointsCloud", null);
  30658. __decorate([
  30659. BABYLON.serialize()
  30660. ], Material.prototype, "fillMode", null);
  30661. BABYLON.Material = Material;
  30662. })(BABYLON || (BABYLON = {}));
  30663. //# sourceMappingURL=babylon.material.js.map
  30664. var BABYLON;
  30665. (function (BABYLON) {
  30666. var PushMaterial = (function (_super) {
  30667. __extends(PushMaterial, _super);
  30668. function PushMaterial(name, scene) {
  30669. var _this = _super.call(this, name, scene) || this;
  30670. _this.storeEffectOnSubMeshes = true;
  30671. return _this;
  30672. }
  30673. PushMaterial.prototype.getEffect = function () {
  30674. return this._activeEffect;
  30675. };
  30676. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  30677. if (!mesh) {
  30678. return false;
  30679. }
  30680. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  30681. return true;
  30682. }
  30683. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  30684. };
  30685. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30686. this._activeEffect.setMatrix("world", world);
  30687. };
  30688. PushMaterial.prototype.bind = function (world, mesh) {
  30689. if (!mesh) {
  30690. return;
  30691. }
  30692. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  30693. };
  30694. PushMaterial.prototype._afterBind = function (mesh, effect) {
  30695. _super.prototype._afterBind.call(this, mesh);
  30696. this.getScene()._cachedEffect = effect;
  30697. };
  30698. PushMaterial.prototype._mustRebind = function (scene, effect) {
  30699. return scene.getCachedEffect() !== effect || scene.getCachedMaterial() !== this;
  30700. };
  30701. PushMaterial.prototype.markAsDirty = function (flag) {
  30702. if (flag & BABYLON.Material.TextureDirtyFlag) {
  30703. this._markAllSubMeshesAsTexturesDirty();
  30704. }
  30705. if (flag & BABYLON.Material.LightDirtyFlag) {
  30706. this._markAllSubMeshesAsLightsDirty();
  30707. }
  30708. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  30709. this._markAllSubMeshesAsFresnelDirty();
  30710. }
  30711. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  30712. this._markAllSubMeshesAsAttributesDirty();
  30713. }
  30714. if (flag & BABYLON.Material.MiscDirtyFlag) {
  30715. this._markAllSubMeshesAsMiscDirty();
  30716. }
  30717. };
  30718. PushMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  30719. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  30720. var mesh = _a[_i];
  30721. if (!mesh.subMeshes) {
  30722. continue;
  30723. }
  30724. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  30725. var subMesh = _c[_b];
  30726. if (subMesh.getMaterial() !== this) {
  30727. continue;
  30728. }
  30729. if (!subMesh._materialDefines) {
  30730. return;
  30731. }
  30732. func(subMesh._materialDefines);
  30733. }
  30734. }
  30735. };
  30736. PushMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  30737. this._markAllSubMeshesAsDirty(function (defines) { return defines._areTexturesDirty = true; });
  30738. };
  30739. PushMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  30740. this._markAllSubMeshesAsDirty(function (defines) { return defines._areFresnelDirty = true; });
  30741. };
  30742. PushMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  30743. this._markAllSubMeshesAsDirty(function (defines) { return defines._areLightsDirty = true; });
  30744. };
  30745. PushMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  30746. this._markAllSubMeshesAsDirty(function (defines) { return defines._areAttributesDirty = true; });
  30747. };
  30748. PushMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  30749. this._markAllSubMeshesAsDirty(function (defines) { return defines._areMiscDirty = true; });
  30750. };
  30751. return PushMaterial;
  30752. }(BABYLON.Material));
  30753. BABYLON.PushMaterial = PushMaterial;
  30754. })(BABYLON || (BABYLON = {}));
  30755. //# sourceMappingURL=babylon.pushMaterial.js.map
  30756. var BABYLON;
  30757. (function (BABYLON) {
  30758. var StandardMaterialDefines = (function (_super) {
  30759. __extends(StandardMaterialDefines, _super);
  30760. function StandardMaterialDefines() {
  30761. var _this = _super.call(this, true) || this;
  30762. _this.DIFFUSE = false;
  30763. _this.AMBIENT = false;
  30764. _this.OPACITY = false;
  30765. _this.OPACITYRGB = false;
  30766. _this.REFLECTION = false;
  30767. _this.EMISSIVE = false;
  30768. _this.SPECULAR = false;
  30769. _this.BUMP = false;
  30770. _this.PARALLAX = false;
  30771. _this.PARALLAXOCCLUSION = false;
  30772. _this.SPECULAROVERALPHA = false;
  30773. _this.CLIPPLANE = false;
  30774. _this.ALPHATEST = false;
  30775. _this.ALPHAFROMDIFFUSE = false;
  30776. _this.POINTSIZE = false;
  30777. _this.FOG = false;
  30778. _this.SPECULARTERM = false;
  30779. _this.DIFFUSEFRESNEL = false;
  30780. _this.OPACITYFRESNEL = false;
  30781. _this.REFLECTIONFRESNEL = false;
  30782. _this.REFRACTIONFRESNEL = false;
  30783. _this.EMISSIVEFRESNEL = false;
  30784. _this.FRESNEL = false;
  30785. _this.NORMAL = false;
  30786. _this.UV1 = false;
  30787. _this.UV2 = false;
  30788. _this.VERTEXCOLOR = false;
  30789. _this.VERTEXALPHA = false;
  30790. _this.NUM_BONE_INFLUENCERS = 0;
  30791. _this.BonesPerMesh = 0;
  30792. _this.INSTANCES = false;
  30793. _this.GLOSSINESS = false;
  30794. _this.ROUGHNESS = false;
  30795. _this.EMISSIVEASILLUMINATION = false;
  30796. _this.LINKEMISSIVEWITHDIFFUSE = false;
  30797. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  30798. _this.LIGHTMAP = false;
  30799. _this.USELIGHTMAPASSHADOWMAP = false;
  30800. _this.REFLECTIONMAP_3D = false;
  30801. _this.REFLECTIONMAP_SPHERICAL = false;
  30802. _this.REFLECTIONMAP_PLANAR = false;
  30803. _this.REFLECTIONMAP_CUBIC = false;
  30804. _this.REFLECTIONMAP_PROJECTION = false;
  30805. _this.REFLECTIONMAP_SKYBOX = false;
  30806. _this.REFLECTIONMAP_EXPLICIT = false;
  30807. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  30808. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  30809. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  30810. _this.INVERTCUBICMAP = false;
  30811. _this.LOGARITHMICDEPTH = false;
  30812. _this.REFRACTION = false;
  30813. _this.REFRACTIONMAP_3D = false;
  30814. _this.REFLECTIONOVERALPHA = false;
  30815. _this.INVERTNORMALMAPX = false;
  30816. _this.INVERTNORMALMAPY = false;
  30817. _this.TWOSIDEDLIGHTING = false;
  30818. _this.SHADOWFULLFLOAT = false;
  30819. _this.CAMERACOLORGRADING = false;
  30820. _this.CAMERACOLORCURVES = false;
  30821. _this.rebuild();
  30822. return _this;
  30823. }
  30824. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  30825. var modes = [
  30826. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  30827. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  30828. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  30829. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  30830. ];
  30831. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  30832. var mode = modes_1[_i];
  30833. this[mode] = (mode === modeToEnable);
  30834. }
  30835. };
  30836. return StandardMaterialDefines;
  30837. }(BABYLON.MaterialDefines));
  30838. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  30839. var StandardMaterial = (function (_super) {
  30840. __extends(StandardMaterial, _super);
  30841. function StandardMaterial(name, scene) {
  30842. var _this = _super.call(this, name, scene) || this;
  30843. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30844. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  30845. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  30846. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30847. _this.specularPower = 64;
  30848. _this._useAlphaFromDiffuseTexture = false;
  30849. _this._useEmissiveAsIllumination = false;
  30850. _this._linkEmissiveWithDiffuse = false;
  30851. _this._useSpecularOverAlpha = false;
  30852. _this._useReflectionOverAlpha = false;
  30853. _this._disableLighting = false;
  30854. _this._useParallax = false;
  30855. _this._useParallaxOcclusion = false;
  30856. _this.parallaxScaleBias = 0.05;
  30857. _this._roughness = 0;
  30858. _this.indexOfRefraction = 0.98;
  30859. _this.invertRefractionY = true;
  30860. _this._useLightmapAsShadowmap = false;
  30861. _this._useReflectionFresnelFromSpecular = false;
  30862. _this._useGlossinessFromSpecularMapAlpha = false;
  30863. _this._maxSimultaneousLights = 4;
  30864. /**
  30865. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30866. */
  30867. _this._invertNormalMapX = false;
  30868. /**
  30869. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30870. */
  30871. _this._invertNormalMapY = false;
  30872. /**
  30873. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30874. */
  30875. _this._twoSidedLighting = false;
  30876. /**
  30877. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30878. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30879. * 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;
  30880. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30881. */
  30882. _this._cameraColorCurves = null;
  30883. _this._renderTargets = new BABYLON.SmartArray(16);
  30884. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30885. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30886. _this.getRenderTargetTextures = function () {
  30887. _this._renderTargets.reset();
  30888. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  30889. _this._renderTargets.push(_this._reflectionTexture);
  30890. }
  30891. if (_this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  30892. _this._renderTargets.push(_this._refractionTexture);
  30893. }
  30894. return _this._renderTargets;
  30895. };
  30896. return _this;
  30897. }
  30898. StandardMaterial.prototype.getClassName = function () {
  30899. return "StandardMaterial";
  30900. };
  30901. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  30902. get: function () {
  30903. return this._useLogarithmicDepth;
  30904. },
  30905. set: function (value) {
  30906. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30907. this._markAllSubMeshesAsMiscDirty();
  30908. },
  30909. enumerable: true,
  30910. configurable: true
  30911. });
  30912. StandardMaterial.prototype.needAlphaBlending = function () {
  30913. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  30914. };
  30915. StandardMaterial.prototype.needAlphaTesting = function () {
  30916. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  30917. };
  30918. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  30919. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  30920. };
  30921. StandardMaterial.prototype.getAlphaTestTexture = function () {
  30922. return this.diffuseTexture;
  30923. };
  30924. /**
  30925. * Child classes can use it to update shaders
  30926. */
  30927. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30928. if (this.isFrozen) {
  30929. if (this._wasPreviouslyReady && subMesh.effect) {
  30930. return true;
  30931. }
  30932. }
  30933. if (!subMesh._materialDefines) {
  30934. subMesh._materialDefines = new StandardMaterialDefines();
  30935. }
  30936. var scene = this.getScene();
  30937. var defines = subMesh._materialDefines;
  30938. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  30939. if (defines._renderId === scene.getRenderId()) {
  30940. return true;
  30941. }
  30942. }
  30943. var engine = scene.getEngine();
  30944. // Lights
  30945. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, this._maxSimultaneousLights, this._disableLighting);
  30946. defines._areLightsDirty = false;
  30947. // Textures
  30948. if (defines._areTexturesDirty) {
  30949. defines._needUVs = false;
  30950. if (scene.texturesEnabled) {
  30951. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30952. if (!this._diffuseTexture.isReady()) {
  30953. return false;
  30954. }
  30955. else {
  30956. defines._needUVs = true;
  30957. defines.DIFFUSE = true;
  30958. }
  30959. }
  30960. else {
  30961. defines.DIFFUSE = false;
  30962. }
  30963. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30964. if (!this._ambientTexture.isReady()) {
  30965. return false;
  30966. }
  30967. else {
  30968. defines._needUVs = true;
  30969. defines.AMBIENT = true;
  30970. }
  30971. }
  30972. else {
  30973. defines.AMBIENT = false;
  30974. }
  30975. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30976. if (!this._opacityTexture.isReady()) {
  30977. return false;
  30978. }
  30979. else {
  30980. defines._needUVs = true;
  30981. defines.OPACITY = true;
  30982. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  30983. }
  30984. }
  30985. else {
  30986. defines.OPACITY = false;
  30987. }
  30988. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30989. if (!this._reflectionTexture.isReady()) {
  30990. return false;
  30991. }
  30992. else {
  30993. defines._needNormals = true;
  30994. defines.REFLECTION = true;
  30995. defines.ROUGHNESS = (this._roughness > 0);
  30996. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  30997. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  30998. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  30999. switch (this._reflectionTexture.coordinatesMode) {
  31000. case BABYLON.Texture.CUBIC_MODE:
  31001. case BABYLON.Texture.INVCUBIC_MODE:
  31002. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  31003. break;
  31004. case BABYLON.Texture.EXPLICIT_MODE:
  31005. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  31006. break;
  31007. case BABYLON.Texture.PLANAR_MODE:
  31008. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  31009. break;
  31010. case BABYLON.Texture.PROJECTION_MODE:
  31011. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  31012. break;
  31013. case BABYLON.Texture.SKYBOX_MODE:
  31014. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  31015. break;
  31016. case BABYLON.Texture.SPHERICAL_MODE:
  31017. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  31018. break;
  31019. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  31020. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  31021. break;
  31022. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  31023. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  31024. break;
  31025. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  31026. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  31027. break;
  31028. }
  31029. }
  31030. }
  31031. else {
  31032. defines.REFLECTION = false;
  31033. }
  31034. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31035. if (!this._emissiveTexture.isReady()) {
  31036. return false;
  31037. }
  31038. else {
  31039. defines._needUVs = true;
  31040. defines.EMISSIVE = true;
  31041. }
  31042. }
  31043. else {
  31044. defines.EMISSIVE = false;
  31045. }
  31046. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31047. if (!this._lightmapTexture.isReady()) {
  31048. return false;
  31049. }
  31050. else {
  31051. defines._needUVs = true;
  31052. defines.LIGHTMAP = true;
  31053. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  31054. }
  31055. }
  31056. else {
  31057. defines.LIGHTMAP = false;
  31058. }
  31059. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31060. if (!this._specularTexture.isReady()) {
  31061. return false;
  31062. }
  31063. else {
  31064. defines._needUVs = true;
  31065. defines.SPECULAR = true;
  31066. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  31067. }
  31068. }
  31069. else {
  31070. defines.SPECULAR = false;
  31071. }
  31072. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  31073. if (!this._bumpTexture.isReady()) {
  31074. return false;
  31075. }
  31076. else {
  31077. defines._needUVs = true;
  31078. defines.BUMP = true;
  31079. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  31080. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  31081. defines.PARALLAX = this._useParallax;
  31082. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  31083. }
  31084. }
  31085. else {
  31086. defines.BUMP = false;
  31087. }
  31088. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31089. if (!this._refractionTexture.isReady()) {
  31090. return false;
  31091. }
  31092. else {
  31093. defines._needUVs = true;
  31094. defines.REFRACTION = true;
  31095. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  31096. }
  31097. }
  31098. else {
  31099. defines.REFRACTION = false;
  31100. }
  31101. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  31102. if (!this._cameraColorGradingTexture.isReady()) {
  31103. return false;
  31104. }
  31105. else {
  31106. defines.CAMERACOLORGRADING = true;
  31107. }
  31108. }
  31109. else {
  31110. defines.CAMERACOLORGRADING = false;
  31111. }
  31112. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  31113. }
  31114. else {
  31115. defines.DIFFUSE = false;
  31116. defines.AMBIENT = false;
  31117. defines.OPACITY = false;
  31118. defines.REFLECTION = false;
  31119. defines.EMISSIVE = false;
  31120. defines.LIGHTMAP = false;
  31121. defines.BUMP = false;
  31122. defines.REFRACTION = false;
  31123. defines.CAMERACOLORGRADING = false;
  31124. }
  31125. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  31126. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  31127. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  31128. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  31129. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  31130. defines._areTexturesDirty = false;
  31131. }
  31132. if (defines._areFresnelDirty) {
  31133. if (StandardMaterial.FresnelEnabled) {
  31134. // Fresnel
  31135. if (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled ||
  31136. this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  31137. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled ||
  31138. this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled ||
  31139. this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled) {
  31140. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  31141. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  31142. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  31143. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  31144. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  31145. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  31146. defines._needNormals = true;
  31147. defines.FRESNEL = true;
  31148. }
  31149. }
  31150. else {
  31151. defines.FRESNEL = false;
  31152. }
  31153. defines._areFresnelDirty = false;
  31154. }
  31155. // Misc.
  31156. if (defines._areMiscDirty) {
  31157. defines.LOGARITHMICDEPTH = this._useLogarithmicDepth;
  31158. defines.POINTSIZE = (this.pointsCloud || scene.forcePointsCloud);
  31159. defines.FOG = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled);
  31160. defines._areMiscDirty = false;
  31161. }
  31162. // Attribs
  31163. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, useInstances);
  31164. defines._areAttributesDirty = false;
  31165. // Values that need to be evaluated on every frame
  31166. defines.CLIPPLANE = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  31167. defines.ALPHATEST = engine.getAlphaTesting();
  31168. defines.INSTANCES = useInstances;
  31169. if (scene._mirroredCameraPosition && defines.BUMP) {
  31170. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  31171. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  31172. }
  31173. // Get correct effect
  31174. if (defines._isDirty) {
  31175. defines._isDirty = false;
  31176. scene.resetCachedMaterial();
  31177. // Fallbacks
  31178. var fallbacks = new BABYLON.EffectFallbacks();
  31179. if (defines.REFLECTION) {
  31180. fallbacks.addFallback(0, "REFLECTION");
  31181. }
  31182. if (defines.SPECULAR) {
  31183. fallbacks.addFallback(0, "SPECULAR");
  31184. }
  31185. if (defines.BUMP) {
  31186. fallbacks.addFallback(0, "BUMP");
  31187. }
  31188. if (defines.PARALLAX) {
  31189. fallbacks.addFallback(1, "PARALLAX");
  31190. }
  31191. if (defines.PARALLAXOCCLUSION) {
  31192. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  31193. }
  31194. if (defines.SPECULAROVERALPHA) {
  31195. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  31196. }
  31197. if (defines.FOG) {
  31198. fallbacks.addFallback(1, "FOG");
  31199. }
  31200. if (defines.POINTSIZE) {
  31201. fallbacks.addFallback(0, "POINTSIZE");
  31202. }
  31203. if (defines.LOGARITHMICDEPTH) {
  31204. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  31205. }
  31206. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  31207. if (defines.SPECULARTERM) {
  31208. fallbacks.addFallback(0, "SPECULARTERM");
  31209. }
  31210. if (defines.DIFFUSEFRESNEL) {
  31211. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  31212. }
  31213. if (defines.OPACITYFRESNEL) {
  31214. fallbacks.addFallback(2, "OPACITYFRESNEL");
  31215. }
  31216. if (defines.REFLECTIONFRESNEL) {
  31217. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  31218. }
  31219. if (defines.EMISSIVEFRESNEL) {
  31220. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  31221. }
  31222. if (defines.FRESNEL) {
  31223. fallbacks.addFallback(4, "FRESNEL");
  31224. }
  31225. //Attributes
  31226. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31227. if (defines.NORMAL) {
  31228. attribs.push(BABYLON.VertexBuffer.NormalKind);
  31229. }
  31230. if (defines.UV1) {
  31231. attribs.push(BABYLON.VertexBuffer.UVKind);
  31232. }
  31233. if (defines.UV2) {
  31234. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31235. }
  31236. if (defines.VERTEXCOLOR) {
  31237. attribs.push(BABYLON.VertexBuffer.ColorKind);
  31238. }
  31239. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  31240. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  31241. var shaderName = "default";
  31242. if (this.customShaderNameResolve) {
  31243. shaderName = this.customShaderNameResolve(shaderName);
  31244. }
  31245. var join = defines.toString();
  31246. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  31247. "vFogInfos", "vFogColor", "pointSize",
  31248. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  31249. "mBones",
  31250. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  31251. "depthValues",
  31252. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  31253. "logarithmicDepthConstant"
  31254. ];
  31255. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  31256. if (defines.CAMERACOLORCURVES) {
  31257. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  31258. }
  31259. if (defines.CAMERACOLORGRADING) {
  31260. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  31261. }
  31262. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, defines, this._maxSimultaneousLights);
  31263. subMesh.setEffect(scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this._maxSimultaneousLights - 1 }), defines);
  31264. }
  31265. if (!subMesh.effect.isReady()) {
  31266. return false;
  31267. }
  31268. defines._renderId = scene.getRenderId();
  31269. this._wasPreviouslyReady = true;
  31270. return true;
  31271. };
  31272. StandardMaterial.prototype.unbind = function () {
  31273. if (this._activeEffect) {
  31274. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  31275. this._activeEffect.setTexture("reflection2DSampler", null);
  31276. }
  31277. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  31278. this._activeEffect.setTexture("refraction2DSampler", null);
  31279. }
  31280. }
  31281. _super.prototype.unbind.call(this);
  31282. };
  31283. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31284. var scene = this.getScene();
  31285. var defines = subMesh._materialDefines;
  31286. if (!defines) {
  31287. return;
  31288. }
  31289. var effect = subMesh.effect;
  31290. this._activeEffect = effect;
  31291. // Matrices
  31292. this.bindOnlyWorldMatrix(world);
  31293. // Bones
  31294. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  31295. if (this._mustRebind(scene, effect)) {
  31296. effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31297. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  31298. // Fresnel
  31299. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  31300. effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  31301. effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  31302. }
  31303. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  31304. effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  31305. }
  31306. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  31307. effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  31308. effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  31309. }
  31310. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  31311. effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  31312. effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  31313. }
  31314. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  31315. effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  31316. effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  31317. }
  31318. }
  31319. // Textures
  31320. if (scene.texturesEnabled) {
  31321. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31322. effect.setTexture("diffuseSampler", this._diffuseTexture);
  31323. effect.setFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  31324. effect.setMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  31325. }
  31326. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31327. effect.setTexture("ambientSampler", this._ambientTexture);
  31328. effect.setFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  31329. effect.setMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  31330. }
  31331. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31332. effect.setTexture("opacitySampler", this._opacityTexture);
  31333. effect.setFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  31334. effect.setMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  31335. }
  31336. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31337. if (this._reflectionTexture.isCube) {
  31338. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  31339. }
  31340. else {
  31341. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  31342. }
  31343. effect.setMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  31344. effect.setFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  31345. }
  31346. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31347. effect.setTexture("emissiveSampler", this._emissiveTexture);
  31348. effect.setFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  31349. effect.setMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  31350. }
  31351. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31352. effect.setTexture("lightmapSampler", this._lightmapTexture);
  31353. effect.setFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  31354. effect.setMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  31355. }
  31356. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31357. effect.setTexture("specularSampler", this._specularTexture);
  31358. effect.setFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  31359. effect.setMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  31360. }
  31361. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  31362. effect.setTexture("bumpSampler", this._bumpTexture);
  31363. effect.setFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  31364. effect.setMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  31365. }
  31366. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31367. var depth = 1.0;
  31368. if (this._refractionTexture.isCube) {
  31369. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  31370. }
  31371. else {
  31372. effect.setTexture("refraction2DSampler", this._refractionTexture);
  31373. effect.setMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  31374. if (this._refractionTexture.depth) {
  31375. depth = this._refractionTexture.depth;
  31376. }
  31377. }
  31378. effect.setFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  31379. }
  31380. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  31381. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  31382. }
  31383. }
  31384. // Clip plane
  31385. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  31386. // Point size
  31387. if (this.pointsCloud) {
  31388. effect.setFloat("pointSize", this.pointSize);
  31389. }
  31390. // Colors
  31391. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  31392. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  31393. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  31394. if (defines.SPECULARTERM) {
  31395. effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  31396. }
  31397. effect.setColor3("vEmissiveColor", this.emissiveColor);
  31398. }
  31399. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  31400. // Diffuse
  31401. effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  31402. // Lights
  31403. if (scene.lightsEnabled && !this.disableLighting) {
  31404. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  31405. }
  31406. // View
  31407. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  31408. effect.setMatrix("view", scene.getViewMatrix());
  31409. }
  31410. // Fog
  31411. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  31412. // Log. depth
  31413. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  31414. // Color Curves
  31415. if (this.cameraColorCurves) {
  31416. BABYLON.ColorCurves.Bind(this.cameraColorCurves, effect);
  31417. }
  31418. }
  31419. this._afterBind(mesh, this._activeEffect);
  31420. };
  31421. StandardMaterial.prototype.getAnimatables = function () {
  31422. var results = [];
  31423. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  31424. results.push(this._diffuseTexture);
  31425. }
  31426. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  31427. results.push(this._ambientTexture);
  31428. }
  31429. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  31430. results.push(this._opacityTexture);
  31431. }
  31432. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  31433. results.push(this._reflectionTexture);
  31434. }
  31435. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  31436. results.push(this._emissiveTexture);
  31437. }
  31438. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  31439. results.push(this._specularTexture);
  31440. }
  31441. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  31442. results.push(this._bumpTexture);
  31443. }
  31444. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  31445. results.push(this._lightmapTexture);
  31446. }
  31447. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  31448. results.push(this._refractionTexture);
  31449. }
  31450. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  31451. results.push(this._cameraColorGradingTexture);
  31452. }
  31453. return results;
  31454. };
  31455. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31456. if (forceDisposeTextures) {
  31457. if (this._diffuseTexture) {
  31458. this._diffuseTexture.dispose();
  31459. }
  31460. if (this._ambientTexture) {
  31461. this._ambientTexture.dispose();
  31462. }
  31463. if (this._opacityTexture) {
  31464. this._opacityTexture.dispose();
  31465. }
  31466. if (this._reflectionTexture) {
  31467. this._reflectionTexture.dispose();
  31468. }
  31469. if (this._emissiveTexture) {
  31470. this._emissiveTexture.dispose();
  31471. }
  31472. if (this._specularTexture) {
  31473. this._specularTexture.dispose();
  31474. }
  31475. if (this._bumpTexture) {
  31476. this._bumpTexture.dispose();
  31477. }
  31478. if (this._lightmapTexture) {
  31479. this._lightmapTexture.dispose();
  31480. }
  31481. if (this._refractionTexture) {
  31482. this._refractionTexture.dispose();
  31483. }
  31484. if (this._cameraColorGradingTexture) {
  31485. this._cameraColorGradingTexture.dispose();
  31486. }
  31487. }
  31488. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  31489. };
  31490. StandardMaterial.prototype.clone = function (name) {
  31491. var _this = this;
  31492. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  31493. };
  31494. StandardMaterial.prototype.serialize = function () {
  31495. return BABYLON.SerializationHelper.Serialize(this);
  31496. };
  31497. // Statics
  31498. StandardMaterial.Parse = function (source, scene, rootUrl) {
  31499. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  31500. };
  31501. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  31502. get: function () {
  31503. return StandardMaterial._DiffuseTextureEnabled;
  31504. },
  31505. set: function (value) {
  31506. if (StandardMaterial._DiffuseTextureEnabled === value) {
  31507. return;
  31508. }
  31509. StandardMaterial._DiffuseTextureEnabled = value;
  31510. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31511. },
  31512. enumerable: true,
  31513. configurable: true
  31514. });
  31515. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  31516. get: function () {
  31517. return StandardMaterial._AmbientTextureEnabled;
  31518. },
  31519. set: function (value) {
  31520. if (StandardMaterial._AmbientTextureEnabled === value) {
  31521. return;
  31522. }
  31523. StandardMaterial._AmbientTextureEnabled = value;
  31524. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31525. },
  31526. enumerable: true,
  31527. configurable: true
  31528. });
  31529. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  31530. get: function () {
  31531. return StandardMaterial._OpacityTextureEnabled;
  31532. },
  31533. set: function (value) {
  31534. if (StandardMaterial._OpacityTextureEnabled === value) {
  31535. return;
  31536. }
  31537. StandardMaterial._OpacityTextureEnabled = value;
  31538. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31539. },
  31540. enumerable: true,
  31541. configurable: true
  31542. });
  31543. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  31544. get: function () {
  31545. return StandardMaterial._ReflectionTextureEnabled;
  31546. },
  31547. set: function (value) {
  31548. if (StandardMaterial._ReflectionTextureEnabled === value) {
  31549. return;
  31550. }
  31551. StandardMaterial._ReflectionTextureEnabled = value;
  31552. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31553. },
  31554. enumerable: true,
  31555. configurable: true
  31556. });
  31557. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  31558. get: function () {
  31559. return StandardMaterial._EmissiveTextureEnabled;
  31560. },
  31561. set: function (value) {
  31562. if (StandardMaterial._EmissiveTextureEnabled === value) {
  31563. return;
  31564. }
  31565. StandardMaterial._EmissiveTextureEnabled = value;
  31566. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31567. },
  31568. enumerable: true,
  31569. configurable: true
  31570. });
  31571. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  31572. get: function () {
  31573. return StandardMaterial._SpecularTextureEnabled;
  31574. },
  31575. set: function (value) {
  31576. if (StandardMaterial._SpecularTextureEnabled === value) {
  31577. return;
  31578. }
  31579. StandardMaterial._SpecularTextureEnabled = value;
  31580. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31581. },
  31582. enumerable: true,
  31583. configurable: true
  31584. });
  31585. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  31586. get: function () {
  31587. return StandardMaterial._BumpTextureEnabled;
  31588. },
  31589. set: function (value) {
  31590. if (StandardMaterial._BumpTextureEnabled === value) {
  31591. return;
  31592. }
  31593. StandardMaterial._BumpTextureEnabled = value;
  31594. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31595. },
  31596. enumerable: true,
  31597. configurable: true
  31598. });
  31599. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  31600. get: function () {
  31601. return StandardMaterial._LightmapTextureEnabled;
  31602. },
  31603. set: function (value) {
  31604. if (StandardMaterial._LightmapTextureEnabled === value) {
  31605. return;
  31606. }
  31607. StandardMaterial._LightmapTextureEnabled = value;
  31608. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31609. },
  31610. enumerable: true,
  31611. configurable: true
  31612. });
  31613. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  31614. get: function () {
  31615. return StandardMaterial._RefractionTextureEnabled;
  31616. },
  31617. set: function (value) {
  31618. if (StandardMaterial._RefractionTextureEnabled === value) {
  31619. return;
  31620. }
  31621. StandardMaterial._RefractionTextureEnabled = value;
  31622. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31623. },
  31624. enumerable: true,
  31625. configurable: true
  31626. });
  31627. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  31628. get: function () {
  31629. return StandardMaterial._ColorGradingTextureEnabled;
  31630. },
  31631. set: function (value) {
  31632. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  31633. return;
  31634. }
  31635. StandardMaterial._ColorGradingTextureEnabled = value;
  31636. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31637. },
  31638. enumerable: true,
  31639. configurable: true
  31640. });
  31641. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  31642. get: function () {
  31643. return StandardMaterial._FresnelEnabled;
  31644. },
  31645. set: function (value) {
  31646. if (StandardMaterial._FresnelEnabled === value) {
  31647. return;
  31648. }
  31649. StandardMaterial._FresnelEnabled = value;
  31650. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  31651. },
  31652. enumerable: true,
  31653. configurable: true
  31654. });
  31655. return StandardMaterial;
  31656. }(BABYLON.PushMaterial));
  31657. // Flags used to enable or disable a type of texture for all Standard Materials
  31658. StandardMaterial._DiffuseTextureEnabled = true;
  31659. StandardMaterial._AmbientTextureEnabled = true;
  31660. StandardMaterial._OpacityTextureEnabled = true;
  31661. StandardMaterial._ReflectionTextureEnabled = true;
  31662. StandardMaterial._EmissiveTextureEnabled = true;
  31663. StandardMaterial._SpecularTextureEnabled = true;
  31664. StandardMaterial._BumpTextureEnabled = true;
  31665. StandardMaterial._LightmapTextureEnabled = true;
  31666. StandardMaterial._RefractionTextureEnabled = true;
  31667. StandardMaterial._ColorGradingTextureEnabled = true;
  31668. StandardMaterial._FresnelEnabled = true;
  31669. __decorate([
  31670. BABYLON.serializeAsTexture("diffuseTexture")
  31671. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  31672. __decorate([
  31673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31674. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  31675. __decorate([
  31676. BABYLON.serializeAsTexture("ambientTexture")
  31677. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  31678. __decorate([
  31679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31680. ], StandardMaterial.prototype, "ambientTexture", void 0);
  31681. __decorate([
  31682. BABYLON.serializeAsTexture("opacityTexture")
  31683. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  31684. __decorate([
  31685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31686. ], StandardMaterial.prototype, "opacityTexture", void 0);
  31687. __decorate([
  31688. BABYLON.serializeAsTexture("reflectionTexture")
  31689. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  31690. __decorate([
  31691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31692. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  31693. __decorate([
  31694. BABYLON.serializeAsTexture("emissiveTexture")
  31695. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  31696. __decorate([
  31697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31698. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  31699. __decorate([
  31700. BABYLON.serializeAsTexture("specularTexture")
  31701. ], StandardMaterial.prototype, "_specularTexture", void 0);
  31702. __decorate([
  31703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31704. ], StandardMaterial.prototype, "specularTexture", void 0);
  31705. __decorate([
  31706. BABYLON.serializeAsTexture("bumpTexture")
  31707. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  31708. __decorate([
  31709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31710. ], StandardMaterial.prototype, "bumpTexture", void 0);
  31711. __decorate([
  31712. BABYLON.serializeAsTexture("lightmapTexture")
  31713. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  31714. __decorate([
  31715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31716. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  31717. __decorate([
  31718. BABYLON.serializeAsTexture("refractionTexture")
  31719. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  31720. __decorate([
  31721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31722. ], StandardMaterial.prototype, "refractionTexture", void 0);
  31723. __decorate([
  31724. BABYLON.serializeAsColor3("ambient")
  31725. ], StandardMaterial.prototype, "ambientColor", void 0);
  31726. __decorate([
  31727. BABYLON.serializeAsColor3("diffuse")
  31728. ], StandardMaterial.prototype, "diffuseColor", void 0);
  31729. __decorate([
  31730. BABYLON.serializeAsColor3("specular")
  31731. ], StandardMaterial.prototype, "specularColor", void 0);
  31732. __decorate([
  31733. BABYLON.serializeAsColor3("emissive")
  31734. ], StandardMaterial.prototype, "emissiveColor", void 0);
  31735. __decorate([
  31736. BABYLON.serialize()
  31737. ], StandardMaterial.prototype, "specularPower", void 0);
  31738. __decorate([
  31739. BABYLON.serialize("useAlphaFromDiffuseTexture")
  31740. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  31741. __decorate([
  31742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31743. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  31744. __decorate([
  31745. BABYLON.serialize("useEmissiveAsIllumination")
  31746. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  31747. __decorate([
  31748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31749. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  31750. __decorate([
  31751. BABYLON.serialize("linkEmissiveWithDiffuse")
  31752. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  31753. __decorate([
  31754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31755. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  31756. __decorate([
  31757. BABYLON.serialize("useSpecularOverAlpha")
  31758. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  31759. __decorate([
  31760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31761. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  31762. __decorate([
  31763. BABYLON.serialize("useReflectionOverAlpha")
  31764. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  31765. __decorate([
  31766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31767. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  31768. __decorate([
  31769. BABYLON.serialize("disableLighting")
  31770. ], StandardMaterial.prototype, "_disableLighting", void 0);
  31771. __decorate([
  31772. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31773. ], StandardMaterial.prototype, "disableLighting", void 0);
  31774. __decorate([
  31775. BABYLON.serialize("useParallax")
  31776. ], StandardMaterial.prototype, "_useParallax", void 0);
  31777. __decorate([
  31778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31779. ], StandardMaterial.prototype, "useParallax", void 0);
  31780. __decorate([
  31781. BABYLON.serialize("useParallaxOcclusion")
  31782. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  31783. __decorate([
  31784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31785. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  31786. __decorate([
  31787. BABYLON.serialize()
  31788. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  31789. __decorate([
  31790. BABYLON.serialize("roughness")
  31791. ], StandardMaterial.prototype, "_roughness", void 0);
  31792. __decorate([
  31793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31794. ], StandardMaterial.prototype, "roughness", void 0);
  31795. __decorate([
  31796. BABYLON.serialize()
  31797. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  31798. __decorate([
  31799. BABYLON.serialize()
  31800. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  31801. __decorate([
  31802. BABYLON.serialize("useLightmapAsShadowmap")
  31803. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  31804. __decorate([
  31805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31806. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  31807. __decorate([
  31808. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  31809. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  31810. __decorate([
  31811. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31812. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  31813. __decorate([
  31814. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  31815. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  31816. __decorate([
  31817. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31818. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  31819. __decorate([
  31820. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  31821. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  31822. __decorate([
  31823. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31824. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  31825. __decorate([
  31826. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  31827. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  31828. __decorate([
  31829. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31830. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  31831. __decorate([
  31832. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  31833. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  31834. __decorate([
  31835. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31836. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  31837. __decorate([
  31838. BABYLON.serialize("useReflectionFresnelFromSpecular")
  31839. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  31840. __decorate([
  31841. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31842. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  31843. __decorate([
  31844. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  31845. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  31846. __decorate([
  31847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31848. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  31849. __decorate([
  31850. BABYLON.serialize("maxSimultaneousLights")
  31851. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  31852. __decorate([
  31853. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31854. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  31855. __decorate([
  31856. BABYLON.serialize("invertNormalMapX")
  31857. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  31858. __decorate([
  31859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31860. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  31861. __decorate([
  31862. BABYLON.serialize("invertNormalMapY")
  31863. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  31864. __decorate([
  31865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31866. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  31867. __decorate([
  31868. BABYLON.serialize("twoSidedLighting")
  31869. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  31870. __decorate([
  31871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31872. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  31873. __decorate([
  31874. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  31875. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  31876. __decorate([
  31877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31878. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  31879. __decorate([
  31880. BABYLON.serializeAsColorCurves("cameraColorCurves")
  31881. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  31882. __decorate([
  31883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31884. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  31885. __decorate([
  31886. BABYLON.serialize()
  31887. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  31888. BABYLON.StandardMaterial = StandardMaterial;
  31889. })(BABYLON || (BABYLON = {}));
  31890. //# sourceMappingURL=babylon.standardMaterial.js.map
  31891. var BABYLON;
  31892. (function (BABYLON) {
  31893. var MultiMaterial = (function (_super) {
  31894. __extends(MultiMaterial, _super);
  31895. function MultiMaterial(name, scene) {
  31896. var _this = _super.call(this, name, scene, true) || this;
  31897. _this.subMaterials = new Array();
  31898. scene.multiMaterials.push(_this);
  31899. return _this;
  31900. }
  31901. // Properties
  31902. MultiMaterial.prototype.getSubMaterial = function (index) {
  31903. if (index < 0 || index >= this.subMaterials.length) {
  31904. return this.getScene().defaultMaterial;
  31905. }
  31906. return this.subMaterials[index];
  31907. };
  31908. // Methods
  31909. MultiMaterial.prototype.getClassName = function () {
  31910. return "MultiMaterial";
  31911. };
  31912. MultiMaterial.prototype.isReady = function (mesh) {
  31913. for (var index = 0; index < this.subMaterials.length; index++) {
  31914. var subMaterial = this.subMaterials[index];
  31915. if (subMaterial) {
  31916. if (!this.subMaterials[index].isReady(mesh)) {
  31917. return false;
  31918. }
  31919. }
  31920. }
  31921. return true;
  31922. };
  31923. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  31924. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  31925. for (var index = 0; index < this.subMaterials.length; index++) {
  31926. var subMaterial = null;
  31927. if (cloneChildren) {
  31928. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  31929. }
  31930. else {
  31931. subMaterial = this.subMaterials[index];
  31932. }
  31933. newMultiMaterial.subMaterials.push(subMaterial);
  31934. }
  31935. return newMultiMaterial;
  31936. };
  31937. MultiMaterial.prototype.serialize = function () {
  31938. var serializationObject = {};
  31939. serializationObject.name = this.name;
  31940. serializationObject.id = this.id;
  31941. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31942. serializationObject.materials = [];
  31943. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  31944. var subMat = this.subMaterials[matIndex];
  31945. if (subMat) {
  31946. serializationObject.materials.push(subMat.id);
  31947. }
  31948. else {
  31949. serializationObject.materials.push(null);
  31950. }
  31951. }
  31952. return serializationObject;
  31953. };
  31954. return MultiMaterial;
  31955. }(BABYLON.Material));
  31956. BABYLON.MultiMaterial = MultiMaterial;
  31957. })(BABYLON || (BABYLON = {}));
  31958. //# sourceMappingURL=babylon.multiMaterial.js.map
  31959. var BABYLON;
  31960. (function (BABYLON) {
  31961. var SceneLoader = (function () {
  31962. function SceneLoader() {
  31963. }
  31964. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  31965. get: function () {
  31966. return 0;
  31967. },
  31968. enumerable: true,
  31969. configurable: true
  31970. });
  31971. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  31972. get: function () {
  31973. return 1;
  31974. },
  31975. enumerable: true,
  31976. configurable: true
  31977. });
  31978. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  31979. get: function () {
  31980. return 2;
  31981. },
  31982. enumerable: true,
  31983. configurable: true
  31984. });
  31985. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  31986. get: function () {
  31987. return 3;
  31988. },
  31989. enumerable: true,
  31990. configurable: true
  31991. });
  31992. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  31993. get: function () {
  31994. return SceneLoader._ForceFullSceneLoadingForIncremental;
  31995. },
  31996. set: function (value) {
  31997. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  31998. },
  31999. enumerable: true,
  32000. configurable: true
  32001. });
  32002. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  32003. get: function () {
  32004. return SceneLoader._ShowLoadingScreen;
  32005. },
  32006. set: function (value) {
  32007. SceneLoader._ShowLoadingScreen = value;
  32008. },
  32009. enumerable: true,
  32010. configurable: true
  32011. });
  32012. Object.defineProperty(SceneLoader, "loggingLevel", {
  32013. get: function () {
  32014. return SceneLoader._loggingLevel;
  32015. },
  32016. set: function (value) {
  32017. SceneLoader._loggingLevel = value;
  32018. },
  32019. enumerable: true,
  32020. configurable: true
  32021. });
  32022. SceneLoader._getDefaultPlugin = function () {
  32023. return SceneLoader._registeredPlugins[".babylon"];
  32024. };
  32025. SceneLoader._getPluginForExtension = function (extension) {
  32026. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  32027. if (registeredPlugin) {
  32028. return registeredPlugin;
  32029. }
  32030. return SceneLoader._getDefaultPlugin();
  32031. };
  32032. SceneLoader._getPluginForFilename = function (sceneFilename) {
  32033. if (sceneFilename.name) {
  32034. sceneFilename = sceneFilename.name;
  32035. }
  32036. var dotPosition = sceneFilename.lastIndexOf(".");
  32037. var queryStringPosition = sceneFilename.indexOf("?");
  32038. if (queryStringPosition === -1) {
  32039. queryStringPosition = sceneFilename.length;
  32040. }
  32041. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  32042. return SceneLoader._getPluginForExtension(extension);
  32043. };
  32044. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  32045. SceneLoader._getDirectLoad = function (sceneFilename) {
  32046. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  32047. return sceneFilename.substr(5);
  32048. }
  32049. return null;
  32050. };
  32051. // Public functions
  32052. SceneLoader.GetPluginForExtension = function (extension) {
  32053. return SceneLoader._getPluginForExtension(extension).plugin;
  32054. };
  32055. SceneLoader.RegisterPlugin = function (plugin) {
  32056. if (typeof plugin.extensions === "string") {
  32057. var extension = plugin.extensions;
  32058. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  32059. plugin: plugin,
  32060. isBinary: false
  32061. };
  32062. }
  32063. else {
  32064. var extensions = plugin.extensions;
  32065. Object.keys(extensions).forEach(function (extension) {
  32066. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  32067. plugin: plugin,
  32068. isBinary: extensions[extension].isBinary
  32069. };
  32070. });
  32071. }
  32072. };
  32073. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  32074. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  32075. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  32076. return;
  32077. }
  32078. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  32079. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  32080. return;
  32081. }
  32082. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  32083. var loadingToken = {};
  32084. scene._addPendingData(loadingToken);
  32085. var manifestChecked = function (success) {
  32086. scene.database = database;
  32087. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  32088. var plugin = registeredPlugin.plugin;
  32089. var useArrayBuffer = registeredPlugin.isBinary;
  32090. var importMeshFromData = function (data) {
  32091. var meshes = [];
  32092. var particleSystems = [];
  32093. var skeletons = [];
  32094. if (scene.isDisposed) {
  32095. if (onerror) {
  32096. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  32097. }
  32098. return;
  32099. }
  32100. try {
  32101. if (plugin.importMesh) {
  32102. var syncedPlugin = plugin;
  32103. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  32104. if (onerror) {
  32105. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  32106. }
  32107. scene._removePendingData(loadingToken);
  32108. return;
  32109. }
  32110. if (onsuccess) {
  32111. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  32112. onsuccess(meshes, particleSystems, skeletons);
  32113. scene._removePendingData(loadingToken);
  32114. }
  32115. }
  32116. else {
  32117. var asyncedPlugin = plugin;
  32118. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  32119. if (onsuccess) {
  32120. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  32121. onsuccess(meshes, particleSystems, skeletons);
  32122. scene._removePendingData(loadingToken);
  32123. }
  32124. }, function () {
  32125. if (onerror) {
  32126. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  32127. }
  32128. scene._removePendingData(loadingToken);
  32129. });
  32130. }
  32131. }
  32132. catch (e) {
  32133. if (onerror) {
  32134. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  32135. }
  32136. scene._removePendingData(loadingToken);
  32137. }
  32138. };
  32139. if (directLoad) {
  32140. importMeshFromData(directLoad);
  32141. return;
  32142. }
  32143. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  32144. importMeshFromData(data);
  32145. }, progressCallBack, database, useArrayBuffer, function () {
  32146. if (onerror) {
  32147. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  32148. }
  32149. });
  32150. };
  32151. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  32152. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  32153. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  32154. }
  32155. else {
  32156. // If the scene is a data stream or offline support is not enabled, it's a direct load
  32157. manifestChecked(true);
  32158. }
  32159. };
  32160. /**
  32161. * Load a scene
  32162. * @param rootUrl a string that defines the root url for scene and resources
  32163. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  32164. * @param engine is the instance of BABYLON.Engine to use to create the scene
  32165. */
  32166. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  32167. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  32168. };
  32169. /**
  32170. * Append a scene
  32171. * @param rootUrl a string that defines the root url for scene and resources
  32172. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  32173. * @param scene is the instance of BABYLON.Scene to append to
  32174. */
  32175. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  32176. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  32177. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  32178. return;
  32179. }
  32180. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  32181. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  32182. var plugin = registeredPlugin.plugin;
  32183. var useArrayBuffer = registeredPlugin.isBinary;
  32184. var database;
  32185. var loadingToken = {};
  32186. scene._addPendingData(loadingToken);
  32187. if (SceneLoader.ShowLoadingScreen) {
  32188. scene.getEngine().displayLoadingUI();
  32189. }
  32190. var loadSceneFromData = function (data) {
  32191. scene.database = database;
  32192. if (plugin.load) {
  32193. var syncedPlugin = plugin;
  32194. if (!syncedPlugin.load(scene, data, rootUrl)) {
  32195. if (onerror) {
  32196. onerror(scene);
  32197. }
  32198. scene._removePendingData(loadingToken);
  32199. scene.getEngine().hideLoadingUI();
  32200. return;
  32201. }
  32202. if (onsuccess) {
  32203. onsuccess(scene);
  32204. }
  32205. scene._removePendingData(loadingToken);
  32206. }
  32207. else {
  32208. var asyncedPlugin = plugin;
  32209. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  32210. if (onsuccess) {
  32211. onsuccess(scene);
  32212. }
  32213. scene._removePendingData(loadingToken);
  32214. }, function () {
  32215. if (onerror) {
  32216. onerror(scene);
  32217. }
  32218. scene._removePendingData(loadingToken);
  32219. scene.getEngine().hideLoadingUI();
  32220. });
  32221. }
  32222. if (SceneLoader.ShowLoadingScreen) {
  32223. scene.executeWhenReady(function () {
  32224. scene.getEngine().hideLoadingUI();
  32225. });
  32226. }
  32227. };
  32228. var manifestChecked = function (success) {
  32229. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  32230. };
  32231. if (directLoad) {
  32232. loadSceneFromData(directLoad);
  32233. return;
  32234. }
  32235. if (rootUrl.indexOf("file:") === -1) {
  32236. if (scene.getEngine().enableOfflineSupport) {
  32237. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  32238. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  32239. }
  32240. else {
  32241. manifestChecked(true);
  32242. }
  32243. }
  32244. else {
  32245. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  32246. }
  32247. };
  32248. return SceneLoader;
  32249. }());
  32250. // Flags
  32251. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  32252. SceneLoader._ShowLoadingScreen = true;
  32253. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  32254. // Members
  32255. SceneLoader._registeredPlugins = {};
  32256. BABYLON.SceneLoader = SceneLoader;
  32257. ;
  32258. })(BABYLON || (BABYLON = {}));
  32259. //# sourceMappingURL=babylon.sceneLoader.js.map
  32260. var BABYLON;
  32261. (function (BABYLON) {
  32262. var Internals;
  32263. (function (Internals) {
  32264. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  32265. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  32266. var parsedMaterial = parsedData.materials[index];
  32267. if (parsedMaterial.id === id) {
  32268. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  32269. }
  32270. }
  32271. return null;
  32272. };
  32273. var isDescendantOf = function (mesh, names, hierarchyIds) {
  32274. names = (names instanceof Array) ? names : [names];
  32275. for (var i in names) {
  32276. if (mesh.name === names[i]) {
  32277. hierarchyIds.push(mesh.id);
  32278. return true;
  32279. }
  32280. }
  32281. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  32282. hierarchyIds.push(mesh.id);
  32283. return true;
  32284. }
  32285. return false;
  32286. };
  32287. var logOperation = function (operation, producer) {
  32288. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  32289. };
  32290. BABYLON.SceneLoader.RegisterPlugin({
  32291. extensions: ".babylon",
  32292. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  32293. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  32294. // when SceneLoader.debugLogging = true (default), or exception encountered.
  32295. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  32296. // and avoid problems with multiple concurrent .babylon loads.
  32297. var log = "importMesh has failed JSON parse";
  32298. try {
  32299. var parsedData = JSON.parse(data);
  32300. log = "";
  32301. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  32302. var loadedSkeletonsIds = [];
  32303. var loadedMaterialsIds = [];
  32304. var hierarchyIds = [];
  32305. var index;
  32306. var cache;
  32307. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  32308. var parsedMesh = parsedData.meshes[index];
  32309. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  32310. if (meshesNames instanceof Array) {
  32311. // Remove found mesh name from list.
  32312. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  32313. }
  32314. //Geometry?
  32315. if (parsedMesh.geometryId) {
  32316. //does the file contain geometries?
  32317. if (parsedData.geometries) {
  32318. //find the correct geometry and add it to the scene
  32319. var found = false;
  32320. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  32321. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  32322. return;
  32323. }
  32324. else {
  32325. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  32326. if (parsedGeometryData.id === parsedMesh.geometryId) {
  32327. switch (geometryType) {
  32328. case "boxes":
  32329. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  32330. break;
  32331. case "spheres":
  32332. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  32333. break;
  32334. case "cylinders":
  32335. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  32336. break;
  32337. case "toruses":
  32338. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  32339. break;
  32340. case "grounds":
  32341. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  32342. break;
  32343. case "planes":
  32344. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  32345. break;
  32346. case "torusKnots":
  32347. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  32348. break;
  32349. case "vertexData":
  32350. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  32351. break;
  32352. }
  32353. found = true;
  32354. }
  32355. });
  32356. }
  32357. });
  32358. if (!found) {
  32359. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  32360. }
  32361. }
  32362. }
  32363. // Material ?
  32364. if (parsedMesh.materialId) {
  32365. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  32366. if (!materialFound && parsedData.multiMaterials) {
  32367. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  32368. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  32369. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  32370. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  32371. var subMatId = parsedMultiMaterial.materials[matIndex];
  32372. loadedMaterialsIds.push(subMatId);
  32373. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  32374. log += "\n\tMaterial " + mat.toString(fullDetails);
  32375. }
  32376. loadedMaterialsIds.push(parsedMultiMaterial.id);
  32377. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  32378. materialFound = true;
  32379. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  32380. break;
  32381. }
  32382. }
  32383. }
  32384. if (!materialFound) {
  32385. loadedMaterialsIds.push(parsedMesh.materialId);
  32386. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  32387. if (!mat) {
  32388. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  32389. }
  32390. else {
  32391. log += "\n\tMaterial " + mat.toString(fullDetails);
  32392. }
  32393. }
  32394. }
  32395. // Skeleton ?
  32396. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  32397. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  32398. if (!skeletonAlreadyLoaded) {
  32399. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  32400. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  32401. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  32402. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  32403. skeletons.push(skeleton);
  32404. loadedSkeletonsIds.push(parsedSkeleton.id);
  32405. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  32406. }
  32407. }
  32408. }
  32409. }
  32410. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  32411. meshes.push(mesh);
  32412. log += "\n\tMesh " + mesh.toString(fullDetails);
  32413. }
  32414. }
  32415. // Connecting parents
  32416. var currentMesh;
  32417. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  32418. currentMesh = scene.meshes[index];
  32419. if (currentMesh._waitingParentId) {
  32420. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  32421. currentMesh._waitingParentId = undefined;
  32422. }
  32423. }
  32424. // freeze and compute world matrix application
  32425. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  32426. currentMesh = scene.meshes[index];
  32427. if (currentMesh._waitingFreezeWorldMatrix) {
  32428. currentMesh.freezeWorldMatrix();
  32429. currentMesh._waitingFreezeWorldMatrix = undefined;
  32430. }
  32431. else {
  32432. currentMesh.computeWorldMatrix(true);
  32433. }
  32434. }
  32435. // Particles
  32436. if (parsedData.particleSystems) {
  32437. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  32438. var parsedParticleSystem = parsedData.particleSystems[index];
  32439. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  32440. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  32441. }
  32442. }
  32443. }
  32444. return true;
  32445. }
  32446. catch (err) {
  32447. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  32448. log = null;
  32449. throw err;
  32450. }
  32451. finally {
  32452. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  32453. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  32454. }
  32455. }
  32456. },
  32457. load: function (scene, data, rootUrl) {
  32458. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  32459. // when SceneLoader.debugLogging = true (default), or exception encountered.
  32460. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  32461. // and avoid problems with multiple concurrent .babylon loads.
  32462. var log = "importScene has failed JSON parse";
  32463. try {
  32464. var parsedData = JSON.parse(data);
  32465. log = "";
  32466. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  32467. // Scene
  32468. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  32469. scene.autoClear = parsedData.autoClear;
  32470. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  32471. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  32472. if (parsedData.gravity) {
  32473. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  32474. }
  32475. // Fog
  32476. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  32477. scene.fogMode = parsedData.fogMode;
  32478. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  32479. scene.fogStart = parsedData.fogStart;
  32480. scene.fogEnd = parsedData.fogEnd;
  32481. scene.fogDensity = parsedData.fogDensity;
  32482. log += "\tFog mode for scene: ";
  32483. switch (scene.fogMode) {
  32484. // getters not compiling, so using hardcoded
  32485. case 1:
  32486. log += "exp\n";
  32487. break;
  32488. case 2:
  32489. log += "exp2\n";
  32490. break;
  32491. case 3:
  32492. log += "linear\n";
  32493. break;
  32494. }
  32495. }
  32496. //Physics
  32497. if (parsedData.physicsEnabled) {
  32498. var physicsPlugin;
  32499. if (parsedData.physicsEngine === "cannon") {
  32500. physicsPlugin = new BABYLON.CannonJSPlugin();
  32501. }
  32502. else if (parsedData.physicsEngine === "oimo") {
  32503. physicsPlugin = new BABYLON.OimoJSPlugin();
  32504. }
  32505. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  32506. //else - default engine, which is currently oimo
  32507. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  32508. scene.enablePhysics(physicsGravity, physicsPlugin);
  32509. }
  32510. // Metadata
  32511. if (parsedData.metadata !== undefined) {
  32512. scene.metadata = parsedData.metadata;
  32513. }
  32514. //collisions, if defined. otherwise, default is true
  32515. if (parsedData.collisionsEnabled != undefined) {
  32516. scene.collisionsEnabled = parsedData.collisionsEnabled;
  32517. }
  32518. scene.workerCollisions = !!parsedData.workerCollisions;
  32519. var index;
  32520. var cache;
  32521. // Lights
  32522. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  32523. var parsedLight = parsedData.lights[index];
  32524. var light = BABYLON.Light.Parse(parsedLight, scene);
  32525. log += (index === 0 ? "\n\tLights:" : "");
  32526. log += "\n\t\t" + light.toString(fullDetails);
  32527. }
  32528. // Animations
  32529. if (parsedData.animations) {
  32530. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  32531. var parsedAnimation = parsedData.animations[index];
  32532. var animation = BABYLON.Animation.Parse(parsedAnimation);
  32533. scene.animations.push(animation);
  32534. log += (index === 0 ? "\n\tAnimations:" : "");
  32535. log += "\n\t\t" + animation.toString(fullDetails);
  32536. }
  32537. }
  32538. if (parsedData.autoAnimate) {
  32539. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  32540. }
  32541. // Materials
  32542. if (parsedData.materials) {
  32543. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  32544. var parsedMaterial = parsedData.materials[index];
  32545. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  32546. log += (index === 0 ? "\n\tMaterials:" : "");
  32547. log += "\n\t\t" + mat.toString(fullDetails);
  32548. }
  32549. }
  32550. if (parsedData.multiMaterials) {
  32551. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  32552. var parsedMultiMaterial = parsedData.multiMaterials[index];
  32553. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  32554. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  32555. log += "\n\t\t" + mmat.toString(fullDetails);
  32556. }
  32557. }
  32558. // Skeletons
  32559. if (parsedData.skeletons) {
  32560. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  32561. var parsedSkeleton = parsedData.skeletons[index];
  32562. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  32563. log += (index === 0 ? "\n\tSkeletons:" : "");
  32564. log += "\n\t\t" + skeleton.toString(fullDetails);
  32565. }
  32566. }
  32567. // Geometries
  32568. var geometries = parsedData.geometries;
  32569. if (geometries) {
  32570. // Boxes
  32571. var boxes = geometries.boxes;
  32572. if (boxes) {
  32573. for (index = 0, cache = boxes.length; index < cache; index++) {
  32574. var parsedBox = boxes[index];
  32575. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  32576. }
  32577. }
  32578. // Spheres
  32579. var spheres = geometries.spheres;
  32580. if (spheres) {
  32581. for (index = 0, cache = spheres.length; index < cache; index++) {
  32582. var parsedSphere = spheres[index];
  32583. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  32584. }
  32585. }
  32586. // Cylinders
  32587. var cylinders = geometries.cylinders;
  32588. if (cylinders) {
  32589. for (index = 0, cache = cylinders.length; index < cache; index++) {
  32590. var parsedCylinder = cylinders[index];
  32591. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  32592. }
  32593. }
  32594. // Toruses
  32595. var toruses = geometries.toruses;
  32596. if (toruses) {
  32597. for (index = 0, cache = toruses.length; index < cache; index++) {
  32598. var parsedTorus = toruses[index];
  32599. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  32600. }
  32601. }
  32602. // Grounds
  32603. var grounds = geometries.grounds;
  32604. if (grounds) {
  32605. for (index = 0, cache = grounds.length; index < cache; index++) {
  32606. var parsedGround = grounds[index];
  32607. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  32608. }
  32609. }
  32610. // Planes
  32611. var planes = geometries.planes;
  32612. if (planes) {
  32613. for (index = 0, cache = planes.length; index < cache; index++) {
  32614. var parsedPlane = planes[index];
  32615. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  32616. }
  32617. }
  32618. // TorusKnots
  32619. var torusKnots = geometries.torusKnots;
  32620. if (torusKnots) {
  32621. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  32622. var parsedTorusKnot = torusKnots[index];
  32623. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  32624. }
  32625. }
  32626. // VertexData
  32627. var vertexData = geometries.vertexData;
  32628. if (vertexData) {
  32629. for (index = 0, cache = vertexData.length; index < cache; index++) {
  32630. var parsedVertexData = vertexData[index];
  32631. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  32632. }
  32633. }
  32634. }
  32635. // Meshes
  32636. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  32637. var parsedMesh = parsedData.meshes[index];
  32638. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  32639. log += (index === 0 ? "\n\tMeshes:" : "");
  32640. log += "\n\t\t" + mesh.toString(fullDetails);
  32641. }
  32642. // Cameras
  32643. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  32644. var parsedCamera = parsedData.cameras[index];
  32645. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  32646. log += (index === 0 ? "\n\tCameras:" : "");
  32647. log += "\n\t\t" + camera.toString(fullDetails);
  32648. }
  32649. if (parsedData.activeCameraID) {
  32650. scene.setActiveCameraByID(parsedData.activeCameraID);
  32651. }
  32652. // Browsing all the graph to connect the dots
  32653. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  32654. var camera = scene.cameras[index];
  32655. if (camera._waitingParentId) {
  32656. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  32657. camera._waitingParentId = undefined;
  32658. }
  32659. }
  32660. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  32661. var light = scene.lights[index];
  32662. if (light._waitingParentId) {
  32663. light.parent = scene.getLastEntryByID(light._waitingParentId);
  32664. light._waitingParentId = undefined;
  32665. }
  32666. }
  32667. // Sounds
  32668. var loadedSounds = [];
  32669. var loadedSound;
  32670. if (BABYLON.AudioEngine && parsedData.sounds) {
  32671. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  32672. var parsedSound = parsedData.sounds[index];
  32673. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32674. if (!parsedSound.url)
  32675. parsedSound.url = parsedSound.name;
  32676. if (!loadedSounds[parsedSound.url]) {
  32677. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  32678. loadedSounds[parsedSound.url] = loadedSound;
  32679. }
  32680. else {
  32681. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  32682. }
  32683. }
  32684. else {
  32685. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  32686. }
  32687. }
  32688. }
  32689. loadedSounds = [];
  32690. // Connect parents & children and parse actions
  32691. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  32692. var mesh = scene.meshes[index];
  32693. if (mesh._waitingParentId) {
  32694. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  32695. mesh._waitingParentId = undefined;
  32696. }
  32697. if (mesh._waitingActions) {
  32698. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  32699. mesh._waitingActions = undefined;
  32700. }
  32701. }
  32702. // freeze world matrix application
  32703. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  32704. var currentMesh = scene.meshes[index];
  32705. if (currentMesh._waitingFreezeWorldMatrix) {
  32706. currentMesh.freezeWorldMatrix();
  32707. currentMesh._waitingFreezeWorldMatrix = undefined;
  32708. }
  32709. else {
  32710. currentMesh.computeWorldMatrix(true);
  32711. }
  32712. }
  32713. // Particles Systems
  32714. if (parsedData.particleSystems) {
  32715. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  32716. var parsedParticleSystem = parsedData.particleSystems[index];
  32717. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  32718. }
  32719. }
  32720. // Lens flares
  32721. if (parsedData.lensFlareSystems) {
  32722. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  32723. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  32724. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  32725. }
  32726. }
  32727. // Shadows
  32728. if (parsedData.shadowGenerators) {
  32729. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  32730. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  32731. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  32732. }
  32733. }
  32734. // Lights exclusions / inclusions
  32735. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  32736. var light = scene.lights[index];
  32737. // Excluded check
  32738. if (light._excludedMeshesIds.length > 0) {
  32739. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  32740. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  32741. if (excludedMesh) {
  32742. light.excludedMeshes.push(excludedMesh);
  32743. }
  32744. }
  32745. light._excludedMeshesIds = [];
  32746. }
  32747. // Included check
  32748. if (light._includedOnlyMeshesIds.length > 0) {
  32749. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  32750. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  32751. if (includedOnlyMesh) {
  32752. light.includedOnlyMeshes.push(includedOnlyMesh);
  32753. }
  32754. }
  32755. light._includedOnlyMeshesIds = [];
  32756. }
  32757. }
  32758. // Actions (scene)
  32759. if (parsedData.actions) {
  32760. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  32761. }
  32762. // Finish
  32763. return true;
  32764. }
  32765. catch (err) {
  32766. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  32767. log = null;
  32768. throw err;
  32769. }
  32770. finally {
  32771. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  32772. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  32773. }
  32774. }
  32775. }
  32776. });
  32777. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32778. })(BABYLON || (BABYLON = {}));
  32779. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  32780. var BABYLON;
  32781. (function (BABYLON) {
  32782. var SpriteManager = (function () {
  32783. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  32784. if (epsilon === void 0) { epsilon = 0.01; }
  32785. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32786. this.name = name;
  32787. this.sprites = new Array();
  32788. this.renderingGroupId = 0;
  32789. this.layerMask = 0x0FFFFFFF;
  32790. this.fogEnabled = true;
  32791. this.isPickable = false;
  32792. /**
  32793. * An event triggered when the manager is disposed.
  32794. * @type {BABYLON.Observable}
  32795. */
  32796. this.onDisposeObservable = new BABYLON.Observable();
  32797. this._vertexBuffers = {};
  32798. this._capacity = capacity;
  32799. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  32800. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32801. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32802. if (cellSize.width && cellSize.height) {
  32803. this.cellWidth = cellSize.width;
  32804. this.cellHeight = cellSize.height;
  32805. }
  32806. else if (cellSize !== undefined) {
  32807. this.cellWidth = cellSize;
  32808. this.cellHeight = cellSize;
  32809. }
  32810. else {
  32811. return;
  32812. }
  32813. this._epsilon = epsilon;
  32814. this._scene = scene;
  32815. this._scene.spriteManagers.push(this);
  32816. var indices = [];
  32817. var index = 0;
  32818. for (var count = 0; count < capacity; count++) {
  32819. indices.push(index);
  32820. indices.push(index + 1);
  32821. indices.push(index + 2);
  32822. indices.push(index);
  32823. indices.push(index + 2);
  32824. indices.push(index + 3);
  32825. index += 4;
  32826. }
  32827. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32828. // VBO
  32829. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  32830. this._vertexData = new Float32Array(capacity * 16 * 4);
  32831. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  32832. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  32833. var options = this._buffer.createVertexBuffer("options", 4, 4);
  32834. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  32835. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  32836. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  32837. this._vertexBuffers["options"] = options;
  32838. this._vertexBuffers["cellInfo"] = cellInfo;
  32839. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  32840. // Effects
  32841. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  32842. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  32843. }
  32844. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  32845. set: function (callback) {
  32846. if (this._onDisposeObserver) {
  32847. this.onDisposeObservable.remove(this._onDisposeObserver);
  32848. }
  32849. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  32850. },
  32851. enumerable: true,
  32852. configurable: true
  32853. });
  32854. Object.defineProperty(SpriteManager.prototype, "texture", {
  32855. get: function () {
  32856. return this._spriteTexture;
  32857. },
  32858. set: function (value) {
  32859. this._spriteTexture = value;
  32860. },
  32861. enumerable: true,
  32862. configurable: true
  32863. });
  32864. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  32865. var arrayOffset = index * 16;
  32866. if (offsetX === 0)
  32867. offsetX = this._epsilon;
  32868. else if (offsetX === 1)
  32869. offsetX = 1 - this._epsilon;
  32870. if (offsetY === 0)
  32871. offsetY = this._epsilon;
  32872. else if (offsetY === 1)
  32873. offsetY = 1 - this._epsilon;
  32874. this._vertexData[arrayOffset] = sprite.position.x;
  32875. this._vertexData[arrayOffset + 1] = sprite.position.y;
  32876. this._vertexData[arrayOffset + 2] = sprite.position.z;
  32877. this._vertexData[arrayOffset + 3] = sprite.angle;
  32878. this._vertexData[arrayOffset + 4] = sprite.width;
  32879. this._vertexData[arrayOffset + 5] = sprite.height;
  32880. this._vertexData[arrayOffset + 6] = offsetX;
  32881. this._vertexData[arrayOffset + 7] = offsetY;
  32882. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  32883. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  32884. var offset = (sprite.cellIndex / rowSize) >> 0;
  32885. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  32886. this._vertexData[arrayOffset + 11] = offset;
  32887. // Color
  32888. this._vertexData[arrayOffset + 12] = sprite.color.r;
  32889. this._vertexData[arrayOffset + 13] = sprite.color.g;
  32890. this._vertexData[arrayOffset + 14] = sprite.color.b;
  32891. this._vertexData[arrayOffset + 15] = sprite.color.a;
  32892. };
  32893. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  32894. var count = Math.min(this._capacity, this.sprites.length);
  32895. var min = BABYLON.Vector3.Zero();
  32896. var max = BABYLON.Vector3.Zero();
  32897. var distance = Number.MAX_VALUE;
  32898. var currentSprite;
  32899. var cameraSpacePosition = BABYLON.Vector3.Zero();
  32900. var cameraView = camera.getViewMatrix();
  32901. for (var index = 0; index < count; index++) {
  32902. var sprite = this.sprites[index];
  32903. if (!sprite) {
  32904. continue;
  32905. }
  32906. if (predicate) {
  32907. if (!predicate(sprite)) {
  32908. continue;
  32909. }
  32910. }
  32911. else if (!sprite.isPickable) {
  32912. continue;
  32913. }
  32914. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  32915. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  32916. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  32917. if (ray.intersectsBoxMinMax(min, max)) {
  32918. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  32919. if (distance > currentDistance) {
  32920. distance = currentDistance;
  32921. currentSprite = sprite;
  32922. if (fastCheck) {
  32923. break;
  32924. }
  32925. }
  32926. }
  32927. }
  32928. if (currentSprite) {
  32929. var result = new BABYLON.PickingInfo();
  32930. result.hit = true;
  32931. result.pickedSprite = currentSprite;
  32932. result.distance = distance;
  32933. return result;
  32934. }
  32935. return null;
  32936. };
  32937. SpriteManager.prototype.render = function () {
  32938. // Check
  32939. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  32940. return;
  32941. var engine = this._scene.getEngine();
  32942. var baseSize = this._spriteTexture.getBaseSize();
  32943. // Sprites
  32944. var deltaTime = engine.getDeltaTime();
  32945. var max = Math.min(this._capacity, this.sprites.length);
  32946. var rowSize = baseSize.width / this.cellWidth;
  32947. var offset = 0;
  32948. for (var index = 0; index < max; index++) {
  32949. var sprite = this.sprites[index];
  32950. if (!sprite) {
  32951. continue;
  32952. }
  32953. sprite._animate(deltaTime);
  32954. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  32955. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  32956. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  32957. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  32958. }
  32959. this._buffer.update(this._vertexData);
  32960. // Render
  32961. var effect = this._effectBase;
  32962. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  32963. effect = this._effectFog;
  32964. }
  32965. engine.enableEffect(effect);
  32966. var viewMatrix = this._scene.getViewMatrix();
  32967. effect.setTexture("diffuseSampler", this._spriteTexture);
  32968. effect.setMatrix("view", viewMatrix);
  32969. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  32970. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  32971. // Fog
  32972. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  32973. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  32974. effect.setColor3("vFogColor", this._scene.fogColor);
  32975. }
  32976. // VBOs
  32977. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32978. // Draw order
  32979. engine.setDepthFunctionToLessOrEqual();
  32980. effect.setBool("alphaTest", true);
  32981. engine.setColorWrite(false);
  32982. engine.draw(true, 0, max * 6);
  32983. engine.setColorWrite(true);
  32984. effect.setBool("alphaTest", false);
  32985. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32986. engine.draw(true, 0, max * 6);
  32987. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32988. };
  32989. SpriteManager.prototype.dispose = function () {
  32990. if (this._buffer) {
  32991. this._buffer.dispose();
  32992. this._buffer = null;
  32993. }
  32994. if (this._indexBuffer) {
  32995. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32996. this._indexBuffer = null;
  32997. }
  32998. if (this._spriteTexture) {
  32999. this._spriteTexture.dispose();
  33000. this._spriteTexture = null;
  33001. }
  33002. // Remove from scene
  33003. var index = this._scene.spriteManagers.indexOf(this);
  33004. this._scene.spriteManagers.splice(index, 1);
  33005. // Callback
  33006. this.onDisposeObservable.notifyObservers(this);
  33007. this.onDisposeObservable.clear();
  33008. };
  33009. return SpriteManager;
  33010. }());
  33011. BABYLON.SpriteManager = SpriteManager;
  33012. })(BABYLON || (BABYLON = {}));
  33013. //# sourceMappingURL=babylon.spriteManager.js.map
  33014. var BABYLON;
  33015. (function (BABYLON) {
  33016. var Sprite = (function () {
  33017. function Sprite(name, manager) {
  33018. this.name = name;
  33019. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  33020. this.width = 1.0;
  33021. this.height = 1.0;
  33022. this.angle = 0;
  33023. this.cellIndex = 0;
  33024. this.invertU = 0;
  33025. this.invertV = 0;
  33026. this.animations = new Array();
  33027. this.isPickable = false;
  33028. this._animationStarted = false;
  33029. this._loopAnimation = false;
  33030. this._fromIndex = 0;
  33031. this._toIndex = 0;
  33032. this._delay = 0;
  33033. this._direction = 1;
  33034. this._frameCount = 0;
  33035. this._time = 0;
  33036. this._manager = manager;
  33037. this._manager.sprites.push(this);
  33038. this.position = BABYLON.Vector3.Zero();
  33039. }
  33040. Object.defineProperty(Sprite.prototype, "size", {
  33041. get: function () {
  33042. return this.width;
  33043. },
  33044. set: function (value) {
  33045. this.width = value;
  33046. this.height = value;
  33047. },
  33048. enumerable: true,
  33049. configurable: true
  33050. });
  33051. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  33052. this._fromIndex = from;
  33053. this._toIndex = to;
  33054. this._loopAnimation = loop;
  33055. this._delay = delay;
  33056. this._animationStarted = true;
  33057. this._direction = from < to ? 1 : -1;
  33058. this.cellIndex = from;
  33059. this._time = 0;
  33060. this._onAnimationEnd = onAnimationEnd;
  33061. };
  33062. Sprite.prototype.stopAnimation = function () {
  33063. this._animationStarted = false;
  33064. };
  33065. Sprite.prototype._animate = function (deltaTime) {
  33066. if (!this._animationStarted)
  33067. return;
  33068. this._time += deltaTime;
  33069. if (this._time > this._delay) {
  33070. this._time = this._time % this._delay;
  33071. this.cellIndex += this._direction;
  33072. if (this.cellIndex === this._toIndex) {
  33073. if (this._loopAnimation) {
  33074. this.cellIndex = this._fromIndex;
  33075. }
  33076. else {
  33077. this._animationStarted = false;
  33078. if (this._onAnimationEnd) {
  33079. this._onAnimationEnd();
  33080. }
  33081. if (this.disposeWhenFinishedAnimating) {
  33082. this.dispose();
  33083. }
  33084. }
  33085. }
  33086. }
  33087. };
  33088. Sprite.prototype.dispose = function () {
  33089. for (var i = 0; i < this._manager.sprites.length; i++) {
  33090. if (this._manager.sprites[i] == this) {
  33091. this._manager.sprites.splice(i, 1);
  33092. }
  33093. }
  33094. };
  33095. return Sprite;
  33096. }());
  33097. BABYLON.Sprite = Sprite;
  33098. })(BABYLON || (BABYLON = {}));
  33099. //# sourceMappingURL=babylon.sprite.js.map
  33100. var BABYLON;
  33101. (function (BABYLON) {
  33102. var Layer = (function () {
  33103. function Layer(name, imgUrl, scene, isBackground, color) {
  33104. this.name = name;
  33105. this.scale = new BABYLON.Vector2(1, 1);
  33106. this.offset = new BABYLON.Vector2(0, 0);
  33107. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  33108. this._vertexBuffers = {};
  33109. // Events
  33110. /**
  33111. * An event triggered when the layer is disposed.
  33112. * @type {BABYLON.Observable}
  33113. */
  33114. this.onDisposeObservable = new BABYLON.Observable();
  33115. /**
  33116. * An event triggered before rendering the scene
  33117. * @type {BABYLON.Observable}
  33118. */
  33119. this.onBeforeRenderObservable = new BABYLON.Observable();
  33120. /**
  33121. * An event triggered after rendering the scene
  33122. * @type {BABYLON.Observable}
  33123. */
  33124. this.onAfterRenderObservable = new BABYLON.Observable();
  33125. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  33126. this.isBackground = isBackground === undefined ? true : isBackground;
  33127. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  33128. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  33129. this._scene.layers.push(this);
  33130. var engine = scene.getEngine();
  33131. // VBO
  33132. var vertices = [];
  33133. vertices.push(1, 1);
  33134. vertices.push(-1, 1);
  33135. vertices.push(-1, -1);
  33136. vertices.push(1, -1);
  33137. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  33138. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  33139. // Indices
  33140. var indices = [];
  33141. indices.push(0);
  33142. indices.push(1);
  33143. indices.push(2);
  33144. indices.push(0);
  33145. indices.push(2);
  33146. indices.push(3);
  33147. this._indexBuffer = engine.createIndexBuffer(indices);
  33148. // Effects
  33149. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  33150. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  33151. }
  33152. Object.defineProperty(Layer.prototype, "onDispose", {
  33153. set: function (callback) {
  33154. if (this._onDisposeObserver) {
  33155. this.onDisposeObservable.remove(this._onDisposeObserver);
  33156. }
  33157. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  33158. },
  33159. enumerable: true,
  33160. configurable: true
  33161. });
  33162. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  33163. set: function (callback) {
  33164. if (this._onBeforeRenderObserver) {
  33165. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  33166. }
  33167. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  33168. },
  33169. enumerable: true,
  33170. configurable: true
  33171. });
  33172. Object.defineProperty(Layer.prototype, "onAfterRender", {
  33173. set: function (callback) {
  33174. if (this._onAfterRenderObserver) {
  33175. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  33176. }
  33177. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  33178. },
  33179. enumerable: true,
  33180. configurable: true
  33181. });
  33182. Layer.prototype.render = function () {
  33183. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  33184. // Check
  33185. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  33186. return;
  33187. var engine = this._scene.getEngine();
  33188. this.onBeforeRenderObservable.notifyObservers(this);
  33189. // Render
  33190. engine.enableEffect(currentEffect);
  33191. engine.setState(false);
  33192. // Texture
  33193. currentEffect.setTexture("textureSampler", this.texture);
  33194. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  33195. // Color
  33196. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  33197. // Scale / offset
  33198. currentEffect.setVector2("offset", this.offset);
  33199. currentEffect.setVector2("scale", this.scale);
  33200. // VBOs
  33201. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  33202. // Draw order
  33203. if (!this.alphaTest) {
  33204. engine.setAlphaMode(this.alphaBlendingMode);
  33205. engine.draw(true, 0, 6);
  33206. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33207. }
  33208. else {
  33209. engine.draw(true, 0, 6);
  33210. }
  33211. this.onAfterRenderObservable.notifyObservers(this);
  33212. };
  33213. Layer.prototype.dispose = function () {
  33214. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33215. if (vertexBuffer) {
  33216. vertexBuffer.dispose();
  33217. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  33218. }
  33219. if (this._indexBuffer) {
  33220. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33221. this._indexBuffer = null;
  33222. }
  33223. if (this.texture) {
  33224. this.texture.dispose();
  33225. this.texture = null;
  33226. }
  33227. // Remove from scene
  33228. var index = this._scene.layers.indexOf(this);
  33229. this._scene.layers.splice(index, 1);
  33230. // Callback
  33231. this.onDisposeObservable.notifyObservers(this);
  33232. this.onDisposeObservable.clear();
  33233. this.onAfterRenderObservable.clear();
  33234. this.onBeforeRenderObservable.clear();
  33235. };
  33236. return Layer;
  33237. }());
  33238. BABYLON.Layer = Layer;
  33239. })(BABYLON || (BABYLON = {}));
  33240. //# sourceMappingURL=babylon.layer.js.map
  33241. var BABYLON;
  33242. (function (BABYLON) {
  33243. var Particle = (function () {
  33244. function Particle() {
  33245. this.position = BABYLON.Vector3.Zero();
  33246. this.direction = BABYLON.Vector3.Zero();
  33247. this.color = new BABYLON.Color4(0, 0, 0, 0);
  33248. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  33249. this.lifeTime = 1.0;
  33250. this.age = 0;
  33251. this.size = 0;
  33252. this.angle = 0;
  33253. this.angularSpeed = 0;
  33254. }
  33255. Particle.prototype.copyTo = function (other) {
  33256. other.position.copyFrom(this.position);
  33257. other.direction.copyFrom(this.direction);
  33258. other.color.copyFrom(this.color);
  33259. other.colorStep.copyFrom(this.colorStep);
  33260. other.lifeTime = this.lifeTime;
  33261. other.age = this.age;
  33262. other.size = this.size;
  33263. other.angle = this.angle;
  33264. other.angularSpeed = this.angularSpeed;
  33265. };
  33266. return Particle;
  33267. }());
  33268. BABYLON.Particle = Particle;
  33269. })(BABYLON || (BABYLON = {}));
  33270. //# sourceMappingURL=babylon.particle.js.map
  33271. var BABYLON;
  33272. (function (BABYLON) {
  33273. var randomNumber = function (min, max) {
  33274. if (min === max) {
  33275. return (min);
  33276. }
  33277. var random = Math.random();
  33278. return ((random * (max - min)) + min);
  33279. };
  33280. var ParticleSystem = (function () {
  33281. function ParticleSystem(name, capacity, scene, customEffect) {
  33282. var _this = this;
  33283. this.name = name;
  33284. // Members
  33285. this.animations = [];
  33286. this.renderingGroupId = 0;
  33287. this.emitter = null;
  33288. this.emitRate = 10;
  33289. this.manualEmitCount = -1;
  33290. this.updateSpeed = 0.01;
  33291. this.targetStopDuration = 0;
  33292. this.disposeOnStop = false;
  33293. this.minEmitPower = 1;
  33294. this.maxEmitPower = 1;
  33295. this.minLifeTime = 1;
  33296. this.maxLifeTime = 1;
  33297. this.minSize = 1;
  33298. this.maxSize = 1;
  33299. this.minAngularSpeed = 0;
  33300. this.maxAngularSpeed = 0;
  33301. this.layerMask = 0x0FFFFFFF;
  33302. this.customShader = null;
  33303. this.preventAutoStart = false;
  33304. /**
  33305. * An event triggered when the system is disposed.
  33306. * @type {BABYLON.Observable}
  33307. */
  33308. this.onDisposeObservable = new BABYLON.Observable();
  33309. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  33310. this.forceDepthWrite = false;
  33311. this.gravity = BABYLON.Vector3.Zero();
  33312. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  33313. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  33314. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  33315. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  33316. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  33317. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  33318. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  33319. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  33320. this.particles = new Array();
  33321. this._stockParticles = new Array();
  33322. this._newPartsExcess = 0;
  33323. this._vertexBuffers = {};
  33324. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  33325. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  33326. this._scaledDirection = BABYLON.Vector3.Zero();
  33327. this._scaledGravity = BABYLON.Vector3.Zero();
  33328. this._currentRenderId = -1;
  33329. this._started = false;
  33330. this._stopped = false;
  33331. this._actualFrame = 0;
  33332. this.id = name;
  33333. this._capacity = capacity;
  33334. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  33335. this._customEffect = customEffect;
  33336. scene.particleSystems.push(this);
  33337. var indices = [];
  33338. var index = 0;
  33339. for (var count = 0; count < capacity; count++) {
  33340. indices.push(index);
  33341. indices.push(index + 1);
  33342. indices.push(index + 2);
  33343. indices.push(index);
  33344. indices.push(index + 2);
  33345. indices.push(index + 3);
  33346. index += 4;
  33347. }
  33348. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  33349. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  33350. this._vertexData = new Float32Array(capacity * 11 * 4);
  33351. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  33352. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  33353. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  33354. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  33355. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  33356. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  33357. this._vertexBuffers["options"] = options;
  33358. // Default behaviors
  33359. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  33360. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  33361. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  33362. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  33363. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  33364. };
  33365. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  33366. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  33367. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  33368. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  33369. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  33370. };
  33371. this.updateFunction = function (particles) {
  33372. for (var index = 0; index < particles.length; index++) {
  33373. var particle = particles[index];
  33374. particle.age += _this._scaledUpdateSpeed;
  33375. if (particle.age >= particle.lifeTime) {
  33376. _this.recycleParticle(particle);
  33377. index--;
  33378. continue;
  33379. }
  33380. else {
  33381. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  33382. particle.color.addInPlace(_this._scaledColorStep);
  33383. if (particle.color.a < 0)
  33384. particle.color.a = 0;
  33385. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  33386. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  33387. particle.position.addInPlace(_this._scaledDirection);
  33388. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  33389. particle.direction.addInPlace(_this._scaledGravity);
  33390. }
  33391. }
  33392. };
  33393. }
  33394. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  33395. set: function (callback) {
  33396. if (this._onDisposeObserver) {
  33397. this.onDisposeObservable.remove(this._onDisposeObserver);
  33398. }
  33399. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  33400. },
  33401. enumerable: true,
  33402. configurable: true
  33403. });
  33404. ParticleSystem.prototype.recycleParticle = function (particle) {
  33405. var lastParticle = this.particles.pop();
  33406. if (lastParticle !== particle) {
  33407. lastParticle.copyTo(particle);
  33408. this._stockParticles.push(lastParticle);
  33409. }
  33410. };
  33411. ParticleSystem.prototype.getCapacity = function () {
  33412. return this._capacity;
  33413. };
  33414. ParticleSystem.prototype.isAlive = function () {
  33415. return this._alive;
  33416. };
  33417. ParticleSystem.prototype.isStarted = function () {
  33418. return this._started;
  33419. };
  33420. ParticleSystem.prototype.start = function () {
  33421. this._started = true;
  33422. this._stopped = false;
  33423. this._actualFrame = 0;
  33424. };
  33425. ParticleSystem.prototype.stop = function () {
  33426. this._stopped = true;
  33427. };
  33428. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  33429. var offset = index * 11;
  33430. this._vertexData[offset] = particle.position.x;
  33431. this._vertexData[offset + 1] = particle.position.y;
  33432. this._vertexData[offset + 2] = particle.position.z;
  33433. this._vertexData[offset + 3] = particle.color.r;
  33434. this._vertexData[offset + 4] = particle.color.g;
  33435. this._vertexData[offset + 5] = particle.color.b;
  33436. this._vertexData[offset + 6] = particle.color.a;
  33437. this._vertexData[offset + 7] = particle.angle;
  33438. this._vertexData[offset + 8] = particle.size;
  33439. this._vertexData[offset + 9] = offsetX;
  33440. this._vertexData[offset + 10] = offsetY;
  33441. };
  33442. ParticleSystem.prototype._update = function (newParticles) {
  33443. // Update current
  33444. this._alive = this.particles.length > 0;
  33445. this.updateFunction(this.particles);
  33446. // Add new ones
  33447. var worldMatrix;
  33448. if (this.emitter.position) {
  33449. worldMatrix = this.emitter.getWorldMatrix();
  33450. }
  33451. else {
  33452. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  33453. }
  33454. var particle;
  33455. for (var index = 0; index < newParticles; index++) {
  33456. if (this.particles.length === this._capacity) {
  33457. break;
  33458. }
  33459. if (this._stockParticles.length !== 0) {
  33460. particle = this._stockParticles.pop();
  33461. particle.age = 0;
  33462. }
  33463. else {
  33464. particle = new BABYLON.Particle();
  33465. }
  33466. this.particles.push(particle);
  33467. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  33468. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  33469. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  33470. particle.size = randomNumber(this.minSize, this.maxSize);
  33471. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  33472. this.startPositionFunction(worldMatrix, particle.position, particle);
  33473. var step = randomNumber(0, 1.0);
  33474. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  33475. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  33476. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  33477. }
  33478. };
  33479. ParticleSystem.prototype._getEffect = function () {
  33480. if (this._customEffect) {
  33481. return this._customEffect;
  33482. }
  33483. ;
  33484. var defines = [];
  33485. if (this._scene.clipPlane) {
  33486. defines.push("#define CLIPPLANE");
  33487. }
  33488. // Effect
  33489. var join = defines.join("\n");
  33490. if (this._cachedDefines !== join) {
  33491. this._cachedDefines = join;
  33492. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  33493. }
  33494. return this._effect;
  33495. };
  33496. ParticleSystem.prototype.animate = function () {
  33497. if (!this._started)
  33498. return;
  33499. var effect = this._getEffect();
  33500. // Check
  33501. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  33502. return;
  33503. if (this._currentRenderId === this._scene.getRenderId()) {
  33504. return;
  33505. }
  33506. this._currentRenderId = this._scene.getRenderId();
  33507. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  33508. // determine the number of particles we need to create
  33509. var newParticles;
  33510. if (this.manualEmitCount > -1) {
  33511. newParticles = this.manualEmitCount;
  33512. this._newPartsExcess = 0;
  33513. this.manualEmitCount = 0;
  33514. }
  33515. else {
  33516. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  33517. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  33518. }
  33519. if (this._newPartsExcess > 1.0) {
  33520. newParticles += this._newPartsExcess >> 0;
  33521. this._newPartsExcess -= this._newPartsExcess >> 0;
  33522. }
  33523. this._alive = false;
  33524. if (!this._stopped) {
  33525. this._actualFrame += this._scaledUpdateSpeed;
  33526. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  33527. this.stop();
  33528. }
  33529. else {
  33530. newParticles = 0;
  33531. }
  33532. this._update(newParticles);
  33533. // Stopped?
  33534. if (this._stopped) {
  33535. if (!this._alive) {
  33536. this._started = false;
  33537. if (this.disposeOnStop) {
  33538. this._scene._toBeDisposed.push(this);
  33539. }
  33540. }
  33541. }
  33542. // Update VBO
  33543. var offset = 0;
  33544. for (var index = 0; index < this.particles.length; index++) {
  33545. var particle = this.particles[index];
  33546. this._appendParticleVertex(offset++, particle, 0, 0);
  33547. this._appendParticleVertex(offset++, particle, 1, 0);
  33548. this._appendParticleVertex(offset++, particle, 1, 1);
  33549. this._appendParticleVertex(offset++, particle, 0, 1);
  33550. }
  33551. this._vertexBuffer.update(this._vertexData);
  33552. };
  33553. ParticleSystem.prototype.render = function () {
  33554. var effect = this._getEffect();
  33555. // Check
  33556. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  33557. return 0;
  33558. var engine = this._scene.getEngine();
  33559. // Render
  33560. engine.enableEffect(effect);
  33561. engine.setState(false);
  33562. var viewMatrix = this._scene.getViewMatrix();
  33563. effect.setTexture("diffuseSampler", this.particleTexture);
  33564. effect.setMatrix("view", viewMatrix);
  33565. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  33566. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  33567. if (this._scene.clipPlane) {
  33568. var clipPlane = this._scene.clipPlane;
  33569. var invView = viewMatrix.clone();
  33570. invView.invert();
  33571. effect.setMatrix("invView", invView);
  33572. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  33573. }
  33574. // VBOs
  33575. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33576. // Draw order
  33577. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  33578. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  33579. }
  33580. else {
  33581. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  33582. }
  33583. if (this.forceDepthWrite) {
  33584. engine.setDepthWrite(true);
  33585. }
  33586. engine.draw(true, 0, this.particles.length * 6);
  33587. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33588. return this.particles.length;
  33589. };
  33590. ParticleSystem.prototype.dispose = function () {
  33591. if (this._vertexBuffer) {
  33592. this._vertexBuffer.dispose();
  33593. this._vertexBuffer = null;
  33594. }
  33595. if (this._indexBuffer) {
  33596. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33597. this._indexBuffer = null;
  33598. }
  33599. if (this.particleTexture) {
  33600. this.particleTexture.dispose();
  33601. this.particleTexture = null;
  33602. }
  33603. // Remove from scene
  33604. var index = this._scene.particleSystems.indexOf(this);
  33605. this._scene.particleSystems.splice(index, 1);
  33606. // Callback
  33607. this.onDisposeObservable.notifyObservers(this);
  33608. this.onDisposeObservable.clear();
  33609. };
  33610. // Clone
  33611. ParticleSystem.prototype.clone = function (name, newEmitter) {
  33612. var custom = null;
  33613. var program = null;
  33614. if (this.customShader != null) {
  33615. program = this.customShader;
  33616. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  33617. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  33618. }
  33619. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  33620. result.customShader = program;
  33621. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  33622. if (newEmitter === undefined) {
  33623. newEmitter = this.emitter;
  33624. }
  33625. result.emitter = newEmitter;
  33626. if (this.particleTexture) {
  33627. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  33628. }
  33629. if (!this.preventAutoStart) {
  33630. result.start();
  33631. }
  33632. return result;
  33633. };
  33634. ParticleSystem.prototype.serialize = function () {
  33635. var serializationObject = {};
  33636. serializationObject.name = this.name;
  33637. serializationObject.id = this.id;
  33638. // Emitter
  33639. if (this.emitter.position) {
  33640. serializationObject.emitterId = this.emitter.id;
  33641. }
  33642. else {
  33643. serializationObject.emitter = this.emitter.asArray();
  33644. }
  33645. serializationObject.capacity = this.getCapacity();
  33646. if (this.particleTexture) {
  33647. serializationObject.textureName = this.particleTexture.name;
  33648. }
  33649. // Animations
  33650. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33651. // Particle system
  33652. serializationObject.minAngularSpeed = this.minAngularSpeed;
  33653. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  33654. serializationObject.minSize = this.minSize;
  33655. serializationObject.maxSize = this.maxSize;
  33656. serializationObject.minEmitPower = this.minEmitPower;
  33657. serializationObject.maxEmitPower = this.maxEmitPower;
  33658. serializationObject.minLifeTime = this.minLifeTime;
  33659. serializationObject.maxLifeTime = this.maxLifeTime;
  33660. serializationObject.emitRate = this.emitRate;
  33661. serializationObject.minEmitBox = this.minEmitBox.asArray();
  33662. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  33663. serializationObject.gravity = this.gravity.asArray();
  33664. serializationObject.direction1 = this.direction1.asArray();
  33665. serializationObject.direction2 = this.direction2.asArray();
  33666. serializationObject.color1 = this.color1.asArray();
  33667. serializationObject.color2 = this.color2.asArray();
  33668. serializationObject.colorDead = this.colorDead.asArray();
  33669. serializationObject.updateSpeed = this.updateSpeed;
  33670. serializationObject.targetStopDuration = this.targetStopDuration;
  33671. serializationObject.textureMask = this.textureMask.asArray();
  33672. serializationObject.blendMode = this.blendMode;
  33673. serializationObject.customShader = this.customShader;
  33674. serializationObject.preventAutoStart = this.preventAutoStart;
  33675. return serializationObject;
  33676. };
  33677. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  33678. var name = parsedParticleSystem.name;
  33679. var custom = null;
  33680. var program = null;
  33681. if (parsedParticleSystem.customShader) {
  33682. program = parsedParticleSystem.customShader;
  33683. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  33684. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  33685. }
  33686. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  33687. particleSystem.customShader = program;
  33688. if (parsedParticleSystem.id) {
  33689. particleSystem.id = parsedParticleSystem.id;
  33690. }
  33691. // Auto start
  33692. if (parsedParticleSystem.preventAutoStart) {
  33693. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  33694. }
  33695. // Texture
  33696. if (parsedParticleSystem.textureName) {
  33697. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  33698. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  33699. }
  33700. // Emitter
  33701. if (parsedParticleSystem.emitterId) {
  33702. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  33703. }
  33704. else {
  33705. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  33706. }
  33707. // Animations
  33708. if (parsedParticleSystem.animations) {
  33709. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  33710. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  33711. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33712. }
  33713. }
  33714. if (parsedParticleSystem.autoAnimate) {
  33715. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  33716. }
  33717. // Particle system
  33718. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  33719. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  33720. particleSystem.minSize = parsedParticleSystem.minSize;
  33721. particleSystem.maxSize = parsedParticleSystem.maxSize;
  33722. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  33723. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  33724. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  33725. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  33726. particleSystem.emitRate = parsedParticleSystem.emitRate;
  33727. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  33728. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  33729. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  33730. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  33731. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  33732. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  33733. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  33734. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  33735. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  33736. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  33737. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  33738. particleSystem.blendMode = parsedParticleSystem.blendMode;
  33739. if (!particleSystem.preventAutoStart) {
  33740. particleSystem.start();
  33741. }
  33742. return particleSystem;
  33743. };
  33744. return ParticleSystem;
  33745. }());
  33746. // Statics
  33747. ParticleSystem.BLENDMODE_ONEONE = 0;
  33748. ParticleSystem.BLENDMODE_STANDARD = 1;
  33749. BABYLON.ParticleSystem = ParticleSystem;
  33750. })(BABYLON || (BABYLON = {}));
  33751. //# sourceMappingURL=babylon.particleSystem.js.map
  33752. var BABYLON;
  33753. (function (BABYLON) {
  33754. var AnimationRange = (function () {
  33755. function AnimationRange(name, from, to) {
  33756. this.name = name;
  33757. this.from = from;
  33758. this.to = to;
  33759. }
  33760. AnimationRange.prototype.clone = function () {
  33761. return new AnimationRange(this.name, this.from, this.to);
  33762. };
  33763. return AnimationRange;
  33764. }());
  33765. BABYLON.AnimationRange = AnimationRange;
  33766. /**
  33767. * Composed of a frame, and an action function
  33768. */
  33769. var AnimationEvent = (function () {
  33770. function AnimationEvent(frame, action, onlyOnce) {
  33771. this.frame = frame;
  33772. this.action = action;
  33773. this.onlyOnce = onlyOnce;
  33774. this.isDone = false;
  33775. }
  33776. return AnimationEvent;
  33777. }());
  33778. BABYLON.AnimationEvent = AnimationEvent;
  33779. var PathCursor = (function () {
  33780. function PathCursor(path) {
  33781. this.path = path;
  33782. this._onchange = new Array();
  33783. this.value = 0;
  33784. this.animations = new Array();
  33785. }
  33786. PathCursor.prototype.getPoint = function () {
  33787. var point = this.path.getPointAtLengthPosition(this.value);
  33788. return new BABYLON.Vector3(point.x, 0, point.y);
  33789. };
  33790. PathCursor.prototype.moveAhead = function (step) {
  33791. if (step === void 0) { step = 0.002; }
  33792. this.move(step);
  33793. return this;
  33794. };
  33795. PathCursor.prototype.moveBack = function (step) {
  33796. if (step === void 0) { step = 0.002; }
  33797. this.move(-step);
  33798. return this;
  33799. };
  33800. PathCursor.prototype.move = function (step) {
  33801. if (Math.abs(step) > 1) {
  33802. throw "step size should be less than 1.";
  33803. }
  33804. this.value += step;
  33805. this.ensureLimits();
  33806. this.raiseOnChange();
  33807. return this;
  33808. };
  33809. PathCursor.prototype.ensureLimits = function () {
  33810. while (this.value > 1) {
  33811. this.value -= 1;
  33812. }
  33813. while (this.value < 0) {
  33814. this.value += 1;
  33815. }
  33816. return this;
  33817. };
  33818. // used by animation engine
  33819. PathCursor.prototype.markAsDirty = function (propertyName) {
  33820. this.ensureLimits();
  33821. this.raiseOnChange();
  33822. return this;
  33823. };
  33824. PathCursor.prototype.raiseOnChange = function () {
  33825. var _this = this;
  33826. this._onchange.forEach(function (f) { return f(_this); });
  33827. return this;
  33828. };
  33829. PathCursor.prototype.onchange = function (f) {
  33830. this._onchange.push(f);
  33831. return this;
  33832. };
  33833. return PathCursor;
  33834. }());
  33835. BABYLON.PathCursor = PathCursor;
  33836. var Animation = (function () {
  33837. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  33838. this.name = name;
  33839. this.targetProperty = targetProperty;
  33840. this.framePerSecond = framePerSecond;
  33841. this.dataType = dataType;
  33842. this.loopMode = loopMode;
  33843. this.enableBlending = enableBlending;
  33844. this._offsetsCache = {};
  33845. this._highLimitsCache = {};
  33846. this._stopped = false;
  33847. this._blendingFactor = 0;
  33848. // The set of event that will be linked to this animation
  33849. this._events = new Array();
  33850. this.allowMatricesInterpolation = false;
  33851. this.blendingSpeed = 0.01;
  33852. this._ranges = {};
  33853. this.targetPropertyPath = targetProperty.split(".");
  33854. this.dataType = dataType;
  33855. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  33856. }
  33857. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  33858. var dataType = undefined;
  33859. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  33860. dataType = Animation.ANIMATIONTYPE_FLOAT;
  33861. }
  33862. else if (from instanceof BABYLON.Quaternion) {
  33863. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  33864. }
  33865. else if (from instanceof BABYLON.Vector3) {
  33866. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  33867. }
  33868. else if (from instanceof BABYLON.Vector2) {
  33869. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  33870. }
  33871. else if (from instanceof BABYLON.Color3) {
  33872. dataType = Animation.ANIMATIONTYPE_COLOR3;
  33873. }
  33874. else if (from instanceof BABYLON.Size) {
  33875. dataType = Animation.ANIMATIONTYPE_SIZE;
  33876. }
  33877. if (dataType == undefined) {
  33878. return null;
  33879. }
  33880. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  33881. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  33882. animation.setKeys(keys);
  33883. if (easingFunction !== undefined) {
  33884. animation.setEasingFunction(easingFunction);
  33885. }
  33886. return animation;
  33887. };
  33888. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  33889. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  33890. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  33891. };
  33892. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  33893. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  33894. node.animations.push(animation);
  33895. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  33896. };
  33897. // Methods
  33898. /**
  33899. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  33900. */
  33901. Animation.prototype.toString = function (fullDetails) {
  33902. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  33903. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  33904. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  33905. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  33906. if (fullDetails) {
  33907. ret += ", Ranges: {";
  33908. var first = true;
  33909. for (var name in this._ranges) {
  33910. if (first) {
  33911. ret += ", ";
  33912. first = false;
  33913. }
  33914. ret += name;
  33915. }
  33916. ret += "}";
  33917. }
  33918. return ret;
  33919. };
  33920. /**
  33921. * Add an event to this animation.
  33922. */
  33923. Animation.prototype.addEvent = function (event) {
  33924. this._events.push(event);
  33925. };
  33926. /**
  33927. * Remove all events found at the given frame
  33928. * @param frame
  33929. */
  33930. Animation.prototype.removeEvents = function (frame) {
  33931. for (var index = 0; index < this._events.length; index++) {
  33932. if (this._events[index].frame === frame) {
  33933. this._events.splice(index, 1);
  33934. index--;
  33935. }
  33936. }
  33937. };
  33938. Animation.prototype.createRange = function (name, from, to) {
  33939. // check name not already in use; could happen for bones after serialized
  33940. if (!this._ranges[name]) {
  33941. this._ranges[name] = new AnimationRange(name, from, to);
  33942. }
  33943. };
  33944. Animation.prototype.deleteRange = function (name, deleteFrames) {
  33945. if (deleteFrames === void 0) { deleteFrames = true; }
  33946. if (this._ranges[name]) {
  33947. if (deleteFrames) {
  33948. var from = this._ranges[name].from;
  33949. var to = this._ranges[name].to;
  33950. // this loop MUST go high to low for multiple splices to work
  33951. for (var key = this._keys.length - 1; key >= 0; key--) {
  33952. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  33953. this._keys.splice(key, 1);
  33954. }
  33955. }
  33956. }
  33957. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  33958. }
  33959. };
  33960. Animation.prototype.getRange = function (name) {
  33961. return this._ranges[name];
  33962. };
  33963. Animation.prototype.reset = function () {
  33964. this._offsetsCache = {};
  33965. this._highLimitsCache = {};
  33966. this.currentFrame = 0;
  33967. this._blendingFactor = 0;
  33968. this._originalBlendValue = null;
  33969. };
  33970. Animation.prototype.isStopped = function () {
  33971. return this._stopped;
  33972. };
  33973. Animation.prototype.getKeys = function () {
  33974. return this._keys;
  33975. };
  33976. Animation.prototype.getHighestFrame = function () {
  33977. var ret = 0;
  33978. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  33979. if (ret < this._keys[key].frame) {
  33980. ret = this._keys[key].frame;
  33981. }
  33982. }
  33983. return ret;
  33984. };
  33985. Animation.prototype.getEasingFunction = function () {
  33986. return this._easingFunction;
  33987. };
  33988. Animation.prototype.setEasingFunction = function (easingFunction) {
  33989. this._easingFunction = easingFunction;
  33990. };
  33991. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  33992. return startValue + (endValue - startValue) * gradient;
  33993. };
  33994. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  33995. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  33996. };
  33997. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  33998. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  33999. };
  34000. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  34001. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  34002. };
  34003. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  34004. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  34005. };
  34006. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  34007. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  34008. };
  34009. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  34010. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  34011. };
  34012. Animation.prototype.clone = function () {
  34013. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  34014. clone.enableBlending = this.enableBlending;
  34015. clone.blendingSpeed = this.blendingSpeed;
  34016. if (this._keys) {
  34017. clone.setKeys(this._keys);
  34018. }
  34019. if (this._ranges) {
  34020. clone._ranges = {};
  34021. for (var name in this._ranges) {
  34022. clone._ranges[name] = this._ranges[name].clone();
  34023. }
  34024. }
  34025. return clone;
  34026. };
  34027. Animation.prototype.setKeys = function (values) {
  34028. this._keys = values.slice(0);
  34029. this._offsetsCache = {};
  34030. this._highLimitsCache = {};
  34031. };
  34032. Animation.prototype._getKeyValue = function (value) {
  34033. if (typeof value === "function") {
  34034. return value();
  34035. }
  34036. return value;
  34037. };
  34038. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  34039. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  34040. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  34041. }
  34042. this.currentFrame = currentFrame;
  34043. // Try to get a hash to find the right key
  34044. 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));
  34045. if (this._keys[startKey].frame >= currentFrame) {
  34046. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  34047. startKey--;
  34048. }
  34049. }
  34050. for (var key = startKey; key < this._keys.length; key++) {
  34051. if (this._keys[key + 1].frame >= currentFrame) {
  34052. var startValue = this._getKeyValue(this._keys[key].value);
  34053. var endValue = this._getKeyValue(this._keys[key + 1].value);
  34054. // gradient : percent of currentFrame between the frame inf and the frame sup
  34055. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  34056. // check for easingFunction and correction of gradient
  34057. if (this._easingFunction != null) {
  34058. gradient = this._easingFunction.ease(gradient);
  34059. }
  34060. switch (this.dataType) {
  34061. // Float
  34062. case Animation.ANIMATIONTYPE_FLOAT:
  34063. switch (loopMode) {
  34064. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34065. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34066. return this.floatInterpolateFunction(startValue, endValue, gradient);
  34067. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34068. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  34069. }
  34070. break;
  34071. // Quaternion
  34072. case Animation.ANIMATIONTYPE_QUATERNION:
  34073. var quaternion = null;
  34074. switch (loopMode) {
  34075. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34076. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34077. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  34078. break;
  34079. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34080. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34081. break;
  34082. }
  34083. return quaternion;
  34084. // Vector3
  34085. case Animation.ANIMATIONTYPE_VECTOR3:
  34086. switch (loopMode) {
  34087. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34088. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34089. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  34090. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34091. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34092. }
  34093. // Vector2
  34094. case Animation.ANIMATIONTYPE_VECTOR2:
  34095. switch (loopMode) {
  34096. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34097. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34098. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  34099. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34100. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34101. }
  34102. // Size
  34103. case Animation.ANIMATIONTYPE_SIZE:
  34104. switch (loopMode) {
  34105. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34106. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34107. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  34108. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34109. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34110. }
  34111. // Color3
  34112. case Animation.ANIMATIONTYPE_COLOR3:
  34113. switch (loopMode) {
  34114. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34115. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34116. return this.color3InterpolateFunction(startValue, endValue, gradient);
  34117. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34118. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34119. }
  34120. // Matrix
  34121. case Animation.ANIMATIONTYPE_MATRIX:
  34122. switch (loopMode) {
  34123. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34124. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34125. if (this.allowMatricesInterpolation) {
  34126. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  34127. }
  34128. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34129. return startValue;
  34130. }
  34131. default:
  34132. break;
  34133. }
  34134. break;
  34135. }
  34136. }
  34137. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  34138. };
  34139. Animation.prototype.setValue = function (currentValue, blend) {
  34140. if (blend === void 0) { blend = false; }
  34141. // Set value
  34142. var path;
  34143. var destination;
  34144. if (this.targetPropertyPath.length > 1) {
  34145. var property = this._target[this.targetPropertyPath[0]];
  34146. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  34147. property = property[this.targetPropertyPath[index]];
  34148. }
  34149. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  34150. destination = property;
  34151. }
  34152. else {
  34153. path = this.targetPropertyPath[0];
  34154. destination = this._target;
  34155. }
  34156. // Blending
  34157. if (this.enableBlending && this._blendingFactor <= 1.0) {
  34158. if (!this._originalBlendValue) {
  34159. if (destination[path].clone) {
  34160. this._originalBlendValue = destination[path].clone();
  34161. }
  34162. else {
  34163. this._originalBlendValue = destination[path];
  34164. }
  34165. }
  34166. if (this._originalBlendValue.prototype) {
  34167. if (this._originalBlendValue.prototype.Lerp) {
  34168. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  34169. }
  34170. else {
  34171. destination[path] = currentValue;
  34172. }
  34173. }
  34174. else if (this._originalBlendValue.m) {
  34175. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  34176. }
  34177. else {
  34178. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  34179. }
  34180. this._blendingFactor += this.blendingSpeed;
  34181. }
  34182. else {
  34183. destination[path] = currentValue;
  34184. }
  34185. if (this._target.markAsDirty) {
  34186. this._target.markAsDirty(this.targetProperty);
  34187. }
  34188. };
  34189. Animation.prototype.goToFrame = function (frame) {
  34190. if (frame < this._keys[0].frame) {
  34191. frame = this._keys[0].frame;
  34192. }
  34193. else if (frame > this._keys[this._keys.length - 1].frame) {
  34194. frame = this._keys[this._keys.length - 1].frame;
  34195. }
  34196. var currentValue = this._interpolate(frame, 0, this.loopMode);
  34197. this.setValue(currentValue);
  34198. };
  34199. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  34200. if (blend === void 0) { blend = false; }
  34201. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  34202. this._stopped = true;
  34203. return false;
  34204. }
  34205. var returnValue = true;
  34206. // Adding a start key at frame 0 if missing
  34207. if (this._keys[0].frame !== 0) {
  34208. var newKey = { frame: 0, value: this._keys[0].value };
  34209. this._keys.splice(0, 0, newKey);
  34210. }
  34211. // Check limits
  34212. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  34213. from = this._keys[0].frame;
  34214. }
  34215. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  34216. to = this._keys[this._keys.length - 1].frame;
  34217. }
  34218. //to and from cannot be the same key
  34219. if (from === to) {
  34220. from++;
  34221. }
  34222. // Compute ratio
  34223. var range = to - from;
  34224. var offsetValue;
  34225. // ratio represents the frame delta between from and to
  34226. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  34227. var highLimitValue = 0;
  34228. if (ratio > range && !loop) {
  34229. returnValue = false;
  34230. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  34231. }
  34232. else {
  34233. // Get max value if required
  34234. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  34235. var keyOffset = to.toString() + from.toString();
  34236. if (!this._offsetsCache[keyOffset]) {
  34237. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  34238. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  34239. switch (this.dataType) {
  34240. // Float
  34241. case Animation.ANIMATIONTYPE_FLOAT:
  34242. this._offsetsCache[keyOffset] = toValue - fromValue;
  34243. break;
  34244. // Quaternion
  34245. case Animation.ANIMATIONTYPE_QUATERNION:
  34246. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34247. break;
  34248. // Vector3
  34249. case Animation.ANIMATIONTYPE_VECTOR3:
  34250. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34251. // Vector2
  34252. case Animation.ANIMATIONTYPE_VECTOR2:
  34253. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34254. // Size
  34255. case Animation.ANIMATIONTYPE_SIZE:
  34256. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34257. // Color3
  34258. case Animation.ANIMATIONTYPE_COLOR3:
  34259. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34260. default:
  34261. break;
  34262. }
  34263. this._highLimitsCache[keyOffset] = toValue;
  34264. }
  34265. highLimitValue = this._highLimitsCache[keyOffset];
  34266. offsetValue = this._offsetsCache[keyOffset];
  34267. }
  34268. }
  34269. if (offsetValue === undefined) {
  34270. switch (this.dataType) {
  34271. // Float
  34272. case Animation.ANIMATIONTYPE_FLOAT:
  34273. offsetValue = 0;
  34274. break;
  34275. // Quaternion
  34276. case Animation.ANIMATIONTYPE_QUATERNION:
  34277. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  34278. break;
  34279. // Vector3
  34280. case Animation.ANIMATIONTYPE_VECTOR3:
  34281. offsetValue = BABYLON.Vector3.Zero();
  34282. break;
  34283. // Vector2
  34284. case Animation.ANIMATIONTYPE_VECTOR2:
  34285. offsetValue = BABYLON.Vector2.Zero();
  34286. break;
  34287. // Size
  34288. case Animation.ANIMATIONTYPE_SIZE:
  34289. offsetValue = BABYLON.Size.Zero();
  34290. break;
  34291. // Color3
  34292. case Animation.ANIMATIONTYPE_COLOR3:
  34293. offsetValue = BABYLON.Color3.Black();
  34294. }
  34295. }
  34296. // Compute value
  34297. var repeatCount = (ratio / range) >> 0;
  34298. var currentFrame = returnValue ? from + ratio % range : to;
  34299. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  34300. // Set value
  34301. this.setValue(currentValue);
  34302. // Check events
  34303. for (var index = 0; index < this._events.length; index++) {
  34304. if (currentFrame >= this._events[index].frame) {
  34305. var event = this._events[index];
  34306. if (!event.isDone) {
  34307. // If event should be done only once, remove it.
  34308. if (event.onlyOnce) {
  34309. this._events.splice(index, 1);
  34310. index--;
  34311. }
  34312. event.isDone = true;
  34313. event.action();
  34314. } // Don't do anything if the event has already be done.
  34315. }
  34316. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  34317. // reset event, the animation is looping
  34318. this._events[index].isDone = false;
  34319. }
  34320. }
  34321. if (!returnValue) {
  34322. this._stopped = true;
  34323. }
  34324. return returnValue;
  34325. };
  34326. Animation.prototype.serialize = function () {
  34327. var serializationObject = {};
  34328. serializationObject.name = this.name;
  34329. serializationObject.property = this.targetProperty;
  34330. serializationObject.framePerSecond = this.framePerSecond;
  34331. serializationObject.dataType = this.dataType;
  34332. serializationObject.loopBehavior = this.loopMode;
  34333. serializationObject.enableBlending = this.enableBlending;
  34334. serializationObject.blendingSpeed = this.blendingSpeed;
  34335. var dataType = this.dataType;
  34336. serializationObject.keys = [];
  34337. var keys = this.getKeys();
  34338. for (var index = 0; index < keys.length; index++) {
  34339. var animationKey = keys[index];
  34340. var key = {};
  34341. key.frame = animationKey.frame;
  34342. switch (dataType) {
  34343. case Animation.ANIMATIONTYPE_FLOAT:
  34344. key.values = [animationKey.value];
  34345. break;
  34346. case Animation.ANIMATIONTYPE_QUATERNION:
  34347. case Animation.ANIMATIONTYPE_MATRIX:
  34348. case Animation.ANIMATIONTYPE_VECTOR3:
  34349. case Animation.ANIMATIONTYPE_COLOR3:
  34350. key.values = animationKey.value.asArray();
  34351. break;
  34352. }
  34353. serializationObject.keys.push(key);
  34354. }
  34355. serializationObject.ranges = [];
  34356. for (var name in this._ranges) {
  34357. var range = {};
  34358. range.name = name;
  34359. range.from = this._ranges[name].from;
  34360. range.to = this._ranges[name].to;
  34361. serializationObject.ranges.push(range);
  34362. }
  34363. return serializationObject;
  34364. };
  34365. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  34366. get: function () {
  34367. return Animation._ANIMATIONTYPE_FLOAT;
  34368. },
  34369. enumerable: true,
  34370. configurable: true
  34371. });
  34372. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  34373. get: function () {
  34374. return Animation._ANIMATIONTYPE_VECTOR3;
  34375. },
  34376. enumerable: true,
  34377. configurable: true
  34378. });
  34379. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  34380. get: function () {
  34381. return Animation._ANIMATIONTYPE_VECTOR2;
  34382. },
  34383. enumerable: true,
  34384. configurable: true
  34385. });
  34386. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  34387. get: function () {
  34388. return Animation._ANIMATIONTYPE_SIZE;
  34389. },
  34390. enumerable: true,
  34391. configurable: true
  34392. });
  34393. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  34394. get: function () {
  34395. return Animation._ANIMATIONTYPE_QUATERNION;
  34396. },
  34397. enumerable: true,
  34398. configurable: true
  34399. });
  34400. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  34401. get: function () {
  34402. return Animation._ANIMATIONTYPE_MATRIX;
  34403. },
  34404. enumerable: true,
  34405. configurable: true
  34406. });
  34407. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  34408. get: function () {
  34409. return Animation._ANIMATIONTYPE_COLOR3;
  34410. },
  34411. enumerable: true,
  34412. configurable: true
  34413. });
  34414. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  34415. get: function () {
  34416. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  34417. },
  34418. enumerable: true,
  34419. configurable: true
  34420. });
  34421. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  34422. get: function () {
  34423. return Animation._ANIMATIONLOOPMODE_CYCLE;
  34424. },
  34425. enumerable: true,
  34426. configurable: true
  34427. });
  34428. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  34429. get: function () {
  34430. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  34431. },
  34432. enumerable: true,
  34433. configurable: true
  34434. });
  34435. Animation.Parse = function (parsedAnimation) {
  34436. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  34437. var dataType = parsedAnimation.dataType;
  34438. var keys = [];
  34439. var data;
  34440. var index;
  34441. if (parsedAnimation.enableBlending) {
  34442. animation.enableBlending = parsedAnimation.enableBlending;
  34443. }
  34444. if (parsedAnimation.blendingSpeed) {
  34445. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  34446. }
  34447. for (index = 0; index < parsedAnimation.keys.length; index++) {
  34448. var key = parsedAnimation.keys[index];
  34449. switch (dataType) {
  34450. case Animation.ANIMATIONTYPE_FLOAT:
  34451. data = key.values[0];
  34452. break;
  34453. case Animation.ANIMATIONTYPE_QUATERNION:
  34454. data = BABYLON.Quaternion.FromArray(key.values);
  34455. break;
  34456. case Animation.ANIMATIONTYPE_MATRIX:
  34457. data = BABYLON.Matrix.FromArray(key.values);
  34458. break;
  34459. case Animation.ANIMATIONTYPE_COLOR3:
  34460. data = BABYLON.Color3.FromArray(key.values);
  34461. break;
  34462. case Animation.ANIMATIONTYPE_VECTOR3:
  34463. default:
  34464. data = BABYLON.Vector3.FromArray(key.values);
  34465. break;
  34466. }
  34467. keys.push({
  34468. frame: key.frame,
  34469. value: data
  34470. });
  34471. }
  34472. animation.setKeys(keys);
  34473. if (parsedAnimation.ranges) {
  34474. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  34475. data = parsedAnimation.ranges[index];
  34476. animation.createRange(data.name, data.from, data.to);
  34477. }
  34478. }
  34479. return animation;
  34480. };
  34481. Animation.AppendSerializedAnimations = function (source, destination) {
  34482. if (source.animations) {
  34483. destination.animations = [];
  34484. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  34485. var animation = source.animations[animationIndex];
  34486. destination.animations.push(animation.serialize());
  34487. }
  34488. }
  34489. };
  34490. return Animation;
  34491. }());
  34492. // Statics
  34493. Animation._ANIMATIONTYPE_FLOAT = 0;
  34494. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  34495. Animation._ANIMATIONTYPE_QUATERNION = 2;
  34496. Animation._ANIMATIONTYPE_MATRIX = 3;
  34497. Animation._ANIMATIONTYPE_COLOR3 = 4;
  34498. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  34499. Animation._ANIMATIONTYPE_SIZE = 6;
  34500. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  34501. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  34502. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  34503. BABYLON.Animation = Animation;
  34504. })(BABYLON || (BABYLON = {}));
  34505. //# sourceMappingURL=babylon.animation.js.map
  34506. var BABYLON;
  34507. (function (BABYLON) {
  34508. var Animatable = (function () {
  34509. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  34510. if (fromFrame === void 0) { fromFrame = 0; }
  34511. if (toFrame === void 0) { toFrame = 100; }
  34512. if (loopAnimation === void 0) { loopAnimation = false; }
  34513. if (speedRatio === void 0) { speedRatio = 1.0; }
  34514. this.target = target;
  34515. this.fromFrame = fromFrame;
  34516. this.toFrame = toFrame;
  34517. this.loopAnimation = loopAnimation;
  34518. this.speedRatio = speedRatio;
  34519. this.onAnimationEnd = onAnimationEnd;
  34520. this._animations = new Array();
  34521. this._paused = false;
  34522. this.animationStarted = false;
  34523. if (animations) {
  34524. this.appendAnimations(target, animations);
  34525. }
  34526. this._scene = scene;
  34527. scene._activeAnimatables.push(this);
  34528. }
  34529. // Methods
  34530. Animatable.prototype.getAnimations = function () {
  34531. return this._animations;
  34532. };
  34533. Animatable.prototype.appendAnimations = function (target, animations) {
  34534. for (var index = 0; index < animations.length; index++) {
  34535. var animation = animations[index];
  34536. animation._target = target;
  34537. this._animations.push(animation);
  34538. }
  34539. };
  34540. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  34541. var animations = this._animations;
  34542. for (var index = 0; index < animations.length; index++) {
  34543. if (animations[index].targetProperty === property) {
  34544. return animations[index];
  34545. }
  34546. }
  34547. return null;
  34548. };
  34549. Animatable.prototype.reset = function () {
  34550. var animations = this._animations;
  34551. for (var index = 0; index < animations.length; index++) {
  34552. animations[index].reset();
  34553. }
  34554. this._localDelayOffset = null;
  34555. this._pausedDelay = null;
  34556. };
  34557. Animatable.prototype.enableBlending = function (blendingSpeed) {
  34558. var animations = this._animations;
  34559. for (var index = 0; index < animations.length; index++) {
  34560. animations[index].enableBlending = true;
  34561. animations[index].blendingSpeed = blendingSpeed;
  34562. }
  34563. };
  34564. Animatable.prototype.disableBlending = function () {
  34565. var animations = this._animations;
  34566. for (var index = 0; index < animations.length; index++) {
  34567. animations[index].enableBlending = false;
  34568. }
  34569. };
  34570. Animatable.prototype.goToFrame = function (frame) {
  34571. var animations = this._animations;
  34572. if (animations[0]) {
  34573. var fps = animations[0].framePerSecond;
  34574. var currentFrame = animations[0].currentFrame;
  34575. var adjustTime = frame - currentFrame;
  34576. var delay = adjustTime * 1000 / fps;
  34577. this._localDelayOffset -= delay;
  34578. }
  34579. for (var index = 0; index < animations.length; index++) {
  34580. animations[index].goToFrame(frame);
  34581. }
  34582. };
  34583. Animatable.prototype.pause = function () {
  34584. if (this._paused) {
  34585. return;
  34586. }
  34587. this._paused = true;
  34588. };
  34589. Animatable.prototype.restart = function () {
  34590. this._paused = false;
  34591. };
  34592. Animatable.prototype.stop = function (animationName) {
  34593. if (animationName) {
  34594. var idx = this._scene._activeAnimatables.indexOf(this);
  34595. if (idx > -1) {
  34596. var animations = this._animations;
  34597. for (var index = animations.length - 1; index >= 0; index--) {
  34598. if (typeof animationName === "string" && animations[index].name != animationName) {
  34599. continue;
  34600. }
  34601. animations[index].reset();
  34602. animations.splice(index, 1);
  34603. }
  34604. if (animations.length == 0) {
  34605. this._scene._activeAnimatables.splice(idx, 1);
  34606. if (this.onAnimationEnd) {
  34607. this.onAnimationEnd();
  34608. }
  34609. }
  34610. }
  34611. }
  34612. else {
  34613. var index = this._scene._activeAnimatables.indexOf(this);
  34614. if (index > -1) {
  34615. this._scene._activeAnimatables.splice(index, 1);
  34616. var animations = this._animations;
  34617. for (var index = 0; index < animations.length; index++) {
  34618. animations[index].reset();
  34619. }
  34620. if (this.onAnimationEnd) {
  34621. this.onAnimationEnd();
  34622. }
  34623. }
  34624. }
  34625. };
  34626. Animatable.prototype._animate = function (delay) {
  34627. if (this._paused) {
  34628. this.animationStarted = false;
  34629. if (!this._pausedDelay) {
  34630. this._pausedDelay = delay;
  34631. }
  34632. return true;
  34633. }
  34634. if (!this._localDelayOffset) {
  34635. this._localDelayOffset = delay;
  34636. }
  34637. else if (this._pausedDelay) {
  34638. this._localDelayOffset += delay - this._pausedDelay;
  34639. this._pausedDelay = null;
  34640. }
  34641. // Animating
  34642. var running = false;
  34643. var animations = this._animations;
  34644. var index;
  34645. for (index = 0; index < animations.length; index++) {
  34646. var animation = animations[index];
  34647. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  34648. running = running || isRunning;
  34649. }
  34650. this.animationStarted = running;
  34651. if (!running) {
  34652. // Remove from active animatables
  34653. index = this._scene._activeAnimatables.indexOf(this);
  34654. this._scene._activeAnimatables.splice(index, 1);
  34655. }
  34656. if (!running && this.onAnimationEnd) {
  34657. this.onAnimationEnd();
  34658. this.onAnimationEnd = null;
  34659. }
  34660. return running;
  34661. };
  34662. return Animatable;
  34663. }());
  34664. BABYLON.Animatable = Animatable;
  34665. })(BABYLON || (BABYLON = {}));
  34666. //# sourceMappingURL=babylon.animatable.js.map
  34667. var BABYLON;
  34668. (function (BABYLON) {
  34669. var EasingFunction = (function () {
  34670. function EasingFunction() {
  34671. // Properties
  34672. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  34673. }
  34674. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  34675. get: function () {
  34676. return EasingFunction._EASINGMODE_EASEIN;
  34677. },
  34678. enumerable: true,
  34679. configurable: true
  34680. });
  34681. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  34682. get: function () {
  34683. return EasingFunction._EASINGMODE_EASEOUT;
  34684. },
  34685. enumerable: true,
  34686. configurable: true
  34687. });
  34688. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  34689. get: function () {
  34690. return EasingFunction._EASINGMODE_EASEINOUT;
  34691. },
  34692. enumerable: true,
  34693. configurable: true
  34694. });
  34695. EasingFunction.prototype.setEasingMode = function (easingMode) {
  34696. var n = Math.min(Math.max(easingMode, 0), 2);
  34697. this._easingMode = n;
  34698. };
  34699. EasingFunction.prototype.getEasingMode = function () {
  34700. return this._easingMode;
  34701. };
  34702. EasingFunction.prototype.easeInCore = function (gradient) {
  34703. throw new Error('You must implement this method');
  34704. };
  34705. EasingFunction.prototype.ease = function (gradient) {
  34706. switch (this._easingMode) {
  34707. case EasingFunction.EASINGMODE_EASEIN:
  34708. return this.easeInCore(gradient);
  34709. case EasingFunction.EASINGMODE_EASEOUT:
  34710. return (1 - this.easeInCore(1 - gradient));
  34711. }
  34712. if (gradient >= 0.5) {
  34713. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  34714. }
  34715. return (this.easeInCore(gradient * 2) * 0.5);
  34716. };
  34717. return EasingFunction;
  34718. }());
  34719. //Statics
  34720. EasingFunction._EASINGMODE_EASEIN = 0;
  34721. EasingFunction._EASINGMODE_EASEOUT = 1;
  34722. EasingFunction._EASINGMODE_EASEINOUT = 2;
  34723. BABYLON.EasingFunction = EasingFunction;
  34724. var CircleEase = (function (_super) {
  34725. __extends(CircleEase, _super);
  34726. function CircleEase() {
  34727. return _super !== null && _super.apply(this, arguments) || this;
  34728. }
  34729. CircleEase.prototype.easeInCore = function (gradient) {
  34730. gradient = Math.max(0, Math.min(1, gradient));
  34731. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  34732. };
  34733. return CircleEase;
  34734. }(EasingFunction));
  34735. BABYLON.CircleEase = CircleEase;
  34736. var BackEase = (function (_super) {
  34737. __extends(BackEase, _super);
  34738. function BackEase(amplitude) {
  34739. if (amplitude === void 0) { amplitude = 1; }
  34740. var _this = _super.call(this) || this;
  34741. _this.amplitude = amplitude;
  34742. return _this;
  34743. }
  34744. BackEase.prototype.easeInCore = function (gradient) {
  34745. var num = Math.max(0, this.amplitude);
  34746. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  34747. };
  34748. return BackEase;
  34749. }(EasingFunction));
  34750. BABYLON.BackEase = BackEase;
  34751. var BounceEase = (function (_super) {
  34752. __extends(BounceEase, _super);
  34753. function BounceEase(bounces, bounciness) {
  34754. if (bounces === void 0) { bounces = 3; }
  34755. if (bounciness === void 0) { bounciness = 2; }
  34756. var _this = _super.call(this) || this;
  34757. _this.bounces = bounces;
  34758. _this.bounciness = bounciness;
  34759. return _this;
  34760. }
  34761. BounceEase.prototype.easeInCore = function (gradient) {
  34762. var y = Math.max(0.0, this.bounces);
  34763. var bounciness = this.bounciness;
  34764. if (bounciness <= 1.0) {
  34765. bounciness = 1.001;
  34766. }
  34767. var num9 = Math.pow(bounciness, y);
  34768. var num5 = 1.0 - bounciness;
  34769. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  34770. var num15 = gradient * num4;
  34771. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  34772. var num3 = Math.floor(num65);
  34773. var num13 = num3 + 1.0;
  34774. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  34775. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  34776. var num7 = (num8 + num12) * 0.5;
  34777. var num6 = gradient - num7;
  34778. var num2 = num7 - num8;
  34779. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  34780. };
  34781. return BounceEase;
  34782. }(EasingFunction));
  34783. BABYLON.BounceEase = BounceEase;
  34784. var CubicEase = (function (_super) {
  34785. __extends(CubicEase, _super);
  34786. function CubicEase() {
  34787. return _super !== null && _super.apply(this, arguments) || this;
  34788. }
  34789. CubicEase.prototype.easeInCore = function (gradient) {
  34790. return (gradient * gradient * gradient);
  34791. };
  34792. return CubicEase;
  34793. }(EasingFunction));
  34794. BABYLON.CubicEase = CubicEase;
  34795. var ElasticEase = (function (_super) {
  34796. __extends(ElasticEase, _super);
  34797. function ElasticEase(oscillations, springiness) {
  34798. if (oscillations === void 0) { oscillations = 3; }
  34799. if (springiness === void 0) { springiness = 3; }
  34800. var _this = _super.call(this) || this;
  34801. _this.oscillations = oscillations;
  34802. _this.springiness = springiness;
  34803. return _this;
  34804. }
  34805. ElasticEase.prototype.easeInCore = function (gradient) {
  34806. var num2;
  34807. var num3 = Math.max(0.0, this.oscillations);
  34808. var num = Math.max(0.0, this.springiness);
  34809. if (num == 0) {
  34810. num2 = gradient;
  34811. }
  34812. else {
  34813. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  34814. }
  34815. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  34816. };
  34817. return ElasticEase;
  34818. }(EasingFunction));
  34819. BABYLON.ElasticEase = ElasticEase;
  34820. var ExponentialEase = (function (_super) {
  34821. __extends(ExponentialEase, _super);
  34822. function ExponentialEase(exponent) {
  34823. if (exponent === void 0) { exponent = 2; }
  34824. var _this = _super.call(this) || this;
  34825. _this.exponent = exponent;
  34826. return _this;
  34827. }
  34828. ExponentialEase.prototype.easeInCore = function (gradient) {
  34829. if (this.exponent <= 0) {
  34830. return gradient;
  34831. }
  34832. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  34833. };
  34834. return ExponentialEase;
  34835. }(EasingFunction));
  34836. BABYLON.ExponentialEase = ExponentialEase;
  34837. var PowerEase = (function (_super) {
  34838. __extends(PowerEase, _super);
  34839. function PowerEase(power) {
  34840. if (power === void 0) { power = 2; }
  34841. var _this = _super.call(this) || this;
  34842. _this.power = power;
  34843. return _this;
  34844. }
  34845. PowerEase.prototype.easeInCore = function (gradient) {
  34846. var y = Math.max(0.0, this.power);
  34847. return Math.pow(gradient, y);
  34848. };
  34849. return PowerEase;
  34850. }(EasingFunction));
  34851. BABYLON.PowerEase = PowerEase;
  34852. var QuadraticEase = (function (_super) {
  34853. __extends(QuadraticEase, _super);
  34854. function QuadraticEase() {
  34855. return _super !== null && _super.apply(this, arguments) || this;
  34856. }
  34857. QuadraticEase.prototype.easeInCore = function (gradient) {
  34858. return (gradient * gradient);
  34859. };
  34860. return QuadraticEase;
  34861. }(EasingFunction));
  34862. BABYLON.QuadraticEase = QuadraticEase;
  34863. var QuarticEase = (function (_super) {
  34864. __extends(QuarticEase, _super);
  34865. function QuarticEase() {
  34866. return _super !== null && _super.apply(this, arguments) || this;
  34867. }
  34868. QuarticEase.prototype.easeInCore = function (gradient) {
  34869. return (gradient * gradient * gradient * gradient);
  34870. };
  34871. return QuarticEase;
  34872. }(EasingFunction));
  34873. BABYLON.QuarticEase = QuarticEase;
  34874. var QuinticEase = (function (_super) {
  34875. __extends(QuinticEase, _super);
  34876. function QuinticEase() {
  34877. return _super !== null && _super.apply(this, arguments) || this;
  34878. }
  34879. QuinticEase.prototype.easeInCore = function (gradient) {
  34880. return (gradient * gradient * gradient * gradient * gradient);
  34881. };
  34882. return QuinticEase;
  34883. }(EasingFunction));
  34884. BABYLON.QuinticEase = QuinticEase;
  34885. var SineEase = (function (_super) {
  34886. __extends(SineEase, _super);
  34887. function SineEase() {
  34888. return _super !== null && _super.apply(this, arguments) || this;
  34889. }
  34890. SineEase.prototype.easeInCore = function (gradient) {
  34891. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  34892. };
  34893. return SineEase;
  34894. }(EasingFunction));
  34895. BABYLON.SineEase = SineEase;
  34896. var BezierCurveEase = (function (_super) {
  34897. __extends(BezierCurveEase, _super);
  34898. function BezierCurveEase(x1, y1, x2, y2) {
  34899. if (x1 === void 0) { x1 = 0; }
  34900. if (y1 === void 0) { y1 = 0; }
  34901. if (x2 === void 0) { x2 = 1; }
  34902. if (y2 === void 0) { y2 = 1; }
  34903. var _this = _super.call(this) || this;
  34904. _this.x1 = x1;
  34905. _this.y1 = y1;
  34906. _this.x2 = x2;
  34907. _this.y2 = y2;
  34908. return _this;
  34909. }
  34910. BezierCurveEase.prototype.easeInCore = function (gradient) {
  34911. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  34912. };
  34913. return BezierCurveEase;
  34914. }(EasingFunction));
  34915. BABYLON.BezierCurveEase = BezierCurveEase;
  34916. })(BABYLON || (BABYLON = {}));
  34917. //# sourceMappingURL=babylon.easing.js.map
  34918. /// <reference path="..\babylon.node.ts" />
  34919. var BABYLON;
  34920. (function (BABYLON) {
  34921. var Bone = (function (_super) {
  34922. __extends(Bone, _super);
  34923. function Bone(name, skeleton, parentBone, matrix, restPose) {
  34924. var _this = _super.call(this, name, skeleton.getScene()) || this;
  34925. _this.name = name;
  34926. _this.children = new Array();
  34927. _this.animations = new Array();
  34928. _this._worldTransform = new BABYLON.Matrix();
  34929. _this._absoluteTransform = new BABYLON.Matrix();
  34930. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  34931. _this._scaleMatrix = BABYLON.Matrix.Identity();
  34932. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  34933. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  34934. _this._scalingDeterminant = 1;
  34935. _this._skeleton = skeleton;
  34936. _this._localMatrix = matrix;
  34937. _this._baseMatrix = matrix.clone();
  34938. _this._restPose = restPose ? restPose : matrix.clone();
  34939. skeleton.bones.push(_this);
  34940. if (parentBone) {
  34941. _this._parent = parentBone;
  34942. parentBone.children.push(_this);
  34943. }
  34944. else {
  34945. _this._parent = null;
  34946. }
  34947. _this._updateDifferenceMatrix();
  34948. if (_this.getAbsoluteTransform().determinant() < 0) {
  34949. _this._scalingDeterminant *= -1;
  34950. }
  34951. return _this;
  34952. }
  34953. Object.defineProperty(Bone.prototype, "_matrix", {
  34954. get: function () {
  34955. return this._localMatrix;
  34956. },
  34957. set: function (val) {
  34958. if (this._localMatrix) {
  34959. this._localMatrix.copyFrom(val);
  34960. }
  34961. else {
  34962. this._localMatrix = val;
  34963. }
  34964. },
  34965. enumerable: true,
  34966. configurable: true
  34967. });
  34968. // Members
  34969. Bone.prototype.getParent = function () {
  34970. return this._parent;
  34971. };
  34972. Bone.prototype.getLocalMatrix = function () {
  34973. return this._localMatrix;
  34974. };
  34975. Bone.prototype.getBaseMatrix = function () {
  34976. return this._baseMatrix;
  34977. };
  34978. Bone.prototype.getRestPose = function () {
  34979. return this._restPose;
  34980. };
  34981. Bone.prototype.returnToRest = function () {
  34982. this.updateMatrix(this._restPose.clone());
  34983. };
  34984. Bone.prototype.getWorldMatrix = function () {
  34985. return this._worldTransform;
  34986. };
  34987. Bone.prototype.getInvertedAbsoluteTransform = function () {
  34988. return this._invertedAbsoluteTransform;
  34989. };
  34990. Bone.prototype.getAbsoluteTransform = function () {
  34991. return this._absoluteTransform;
  34992. };
  34993. // Methods
  34994. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  34995. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  34996. this._baseMatrix = matrix.clone();
  34997. this._localMatrix = matrix.clone();
  34998. this._skeleton._markAsDirty();
  34999. if (updateDifferenceMatrix) {
  35000. this._updateDifferenceMatrix();
  35001. }
  35002. };
  35003. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  35004. if (!rootMatrix) {
  35005. rootMatrix = this._baseMatrix;
  35006. }
  35007. if (this._parent) {
  35008. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  35009. }
  35010. else {
  35011. this._absoluteTransform.copyFrom(rootMatrix);
  35012. }
  35013. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  35014. for (var index = 0; index < this.children.length; index++) {
  35015. this.children[index]._updateDifferenceMatrix();
  35016. }
  35017. };
  35018. Bone.prototype.markAsDirty = function () {
  35019. this._currentRenderId++;
  35020. this._skeleton._markAsDirty();
  35021. };
  35022. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  35023. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  35024. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  35025. // all animation may be coming from a library skeleton, so may need to create animation
  35026. if (this.animations.length === 0) {
  35027. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  35028. this.animations[0].setKeys([]);
  35029. }
  35030. // get animation info / verify there is such a range from the source bone
  35031. var sourceRange = source.animations[0].getRange(rangeName);
  35032. if (!sourceRange) {
  35033. return false;
  35034. }
  35035. var from = sourceRange.from;
  35036. var to = sourceRange.to;
  35037. var sourceKeys = source.animations[0].getKeys();
  35038. // rescaling prep
  35039. var sourceBoneLength = source.length;
  35040. var sourceParent = source.getParent();
  35041. var parent = this.getParent();
  35042. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  35043. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  35044. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  35045. var destKeys = this.animations[0].getKeys();
  35046. // loop vars declaration
  35047. var orig;
  35048. var origTranslation;
  35049. var mat;
  35050. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  35051. orig = sourceKeys[key];
  35052. if (orig.frame >= from && orig.frame <= to) {
  35053. if (rescaleAsRequired) {
  35054. mat = orig.value.clone();
  35055. // scale based on parent ratio, when bone has parent
  35056. if (parentScalingReqd) {
  35057. origTranslation = mat.getTranslation();
  35058. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  35059. // scale based on skeleton dimension ratio when root bone, and value is passed
  35060. }
  35061. else if (dimensionsScalingReqd) {
  35062. origTranslation = mat.getTranslation();
  35063. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  35064. // use original when root bone, and no data for skelDimensionsRatio
  35065. }
  35066. else {
  35067. mat = orig.value;
  35068. }
  35069. }
  35070. else {
  35071. mat = orig.value;
  35072. }
  35073. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  35074. }
  35075. }
  35076. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  35077. return true;
  35078. };
  35079. /**
  35080. * Translate the bone in local or world space.
  35081. * @param vec The amount to translate the bone.
  35082. * @param space The space that the translation is in.
  35083. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35084. */
  35085. Bone.prototype.translate = function (vec, space, mesh) {
  35086. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35087. var lm = this.getLocalMatrix();
  35088. if (space == BABYLON.Space.LOCAL) {
  35089. lm.m[12] += vec.x;
  35090. lm.m[13] += vec.y;
  35091. lm.m[14] += vec.z;
  35092. }
  35093. else {
  35094. var wm;
  35095. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  35096. if (mesh) {
  35097. wm = mesh.getWorldMatrix();
  35098. }
  35099. this._skeleton.computeAbsoluteTransforms();
  35100. var tmat = BABYLON.Tmp.Matrix[0];
  35101. var tvec = BABYLON.Tmp.Vector3[0];
  35102. if (mesh) {
  35103. tmat.copyFrom(this._parent.getAbsoluteTransform());
  35104. tmat.multiplyToRef(wm, tmat);
  35105. }
  35106. else {
  35107. tmat.copyFrom(this._parent.getAbsoluteTransform());
  35108. }
  35109. tmat.m[12] = 0;
  35110. tmat.m[13] = 0;
  35111. tmat.m[14] = 0;
  35112. tmat.invert();
  35113. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  35114. lm.m[12] += tvec.x;
  35115. lm.m[13] += tvec.y;
  35116. lm.m[14] += tvec.z;
  35117. }
  35118. this.markAsDirty();
  35119. };
  35120. /**
  35121. * Set the postion of the bone in local or world space.
  35122. * @param position The position to set the bone.
  35123. * @param space The space that the position is in.
  35124. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35125. */
  35126. Bone.prototype.setPosition = function (position, space, mesh) {
  35127. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35128. var lm = this.getLocalMatrix();
  35129. if (space == BABYLON.Space.LOCAL) {
  35130. lm.m[12] = position.x;
  35131. lm.m[13] = position.y;
  35132. lm.m[14] = position.z;
  35133. }
  35134. else {
  35135. var wm;
  35136. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  35137. if (mesh) {
  35138. wm = mesh.getWorldMatrix();
  35139. }
  35140. this._skeleton.computeAbsoluteTransforms();
  35141. var tmat = BABYLON.Tmp.Matrix[0];
  35142. var vec = BABYLON.Tmp.Vector3[0];
  35143. if (mesh) {
  35144. tmat.copyFrom(this._parent.getAbsoluteTransform());
  35145. tmat.multiplyToRef(wm, tmat);
  35146. }
  35147. else {
  35148. tmat.copyFrom(this._parent.getAbsoluteTransform());
  35149. }
  35150. tmat.invert();
  35151. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  35152. lm.m[12] = vec.x;
  35153. lm.m[13] = vec.y;
  35154. lm.m[14] = vec.z;
  35155. }
  35156. this.markAsDirty();
  35157. };
  35158. /**
  35159. * Set the absolute postion of the bone (world space).
  35160. * @param position The position to set the bone.
  35161. * @param mesh The mesh that this bone is attached to.
  35162. */
  35163. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  35164. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  35165. };
  35166. /**
  35167. * Set the scale of the bone on the x, y and z axes.
  35168. * @param x The scale of the bone on the x axis.
  35169. * @param x The scale of the bone on the y axis.
  35170. * @param z The scale of the bone on the z axis.
  35171. * @param scaleChildren Set this to true if children of the bone should be scaled.
  35172. */
  35173. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  35174. if (scaleChildren === void 0) { scaleChildren = false; }
  35175. if (this.animations[0] && !this.animations[0].isStopped()) {
  35176. if (!scaleChildren) {
  35177. this._negateScaleChildren.x = 1 / x;
  35178. this._negateScaleChildren.y = 1 / y;
  35179. this._negateScaleChildren.z = 1 / z;
  35180. }
  35181. this._syncScaleVector();
  35182. }
  35183. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  35184. };
  35185. /**
  35186. * Scale the bone on the x, y and z axes.
  35187. * @param x The amount to scale the bone on the x axis.
  35188. * @param x The amount to scale the bone on the y axis.
  35189. * @param z The amount to scale the bone on the z axis.
  35190. * @param scaleChildren Set this to true if children of the bone should be scaled.
  35191. */
  35192. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  35193. if (scaleChildren === void 0) { scaleChildren = false; }
  35194. var locMat = this.getLocalMatrix();
  35195. var origLocMat = BABYLON.Tmp.Matrix[0];
  35196. origLocMat.copyFrom(locMat);
  35197. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  35198. origLocMatInv.copyFrom(origLocMat);
  35199. origLocMatInv.invert();
  35200. var scaleMat = BABYLON.Tmp.Matrix[2];
  35201. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  35202. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  35203. this._scaleVector.x *= x;
  35204. this._scaleVector.y *= y;
  35205. this._scaleVector.z *= z;
  35206. locMat.multiplyToRef(origLocMatInv, locMat);
  35207. locMat.multiplyToRef(scaleMat, locMat);
  35208. locMat.multiplyToRef(origLocMat, locMat);
  35209. var parent = this.getParent();
  35210. if (parent) {
  35211. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  35212. }
  35213. else {
  35214. this.getAbsoluteTransform().copyFrom(locMat);
  35215. }
  35216. var len = this.children.length;
  35217. scaleMat.invert();
  35218. for (var i = 0; i < len; i++) {
  35219. var child = this.children[i];
  35220. var cm = child.getLocalMatrix();
  35221. cm.multiplyToRef(scaleMat, cm);
  35222. var lm = child.getLocalMatrix();
  35223. lm.m[12] *= x;
  35224. lm.m[13] *= y;
  35225. lm.m[14] *= z;
  35226. }
  35227. this.computeAbsoluteTransforms();
  35228. if (scaleChildren) {
  35229. for (var i = 0; i < len; i++) {
  35230. this.children[i].scale(x, y, z, scaleChildren);
  35231. }
  35232. }
  35233. this.markAsDirty();
  35234. };
  35235. /**
  35236. * Set the yaw, pitch, and roll of the bone in local or world space.
  35237. * @param yaw The rotation of the bone on the y axis.
  35238. * @param pitch The rotation of the bone on the x axis.
  35239. * @param roll The rotation of the bone on the z axis.
  35240. * @param space The space that the axes of rotation are in.
  35241. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35242. */
  35243. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  35244. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35245. var rotMat = BABYLON.Tmp.Matrix[0];
  35246. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  35247. var rotMatInv = BABYLON.Tmp.Matrix[1];
  35248. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  35249. rotMatInv.multiplyToRef(rotMat, rotMat);
  35250. this._rotateWithMatrix(rotMat, space, mesh);
  35251. };
  35252. /**
  35253. * Rotate the bone on an axis in local or world space.
  35254. * @param axis The axis to rotate the bone on.
  35255. * @param amount The amount to rotate the bone.
  35256. * @param space The space that the axis is in.
  35257. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35258. */
  35259. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  35260. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35261. var rmat = BABYLON.Tmp.Matrix[0];
  35262. rmat.m[12] = 0;
  35263. rmat.m[13] = 0;
  35264. rmat.m[14] = 0;
  35265. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  35266. this._rotateWithMatrix(rmat, space, mesh);
  35267. };
  35268. /**
  35269. * Set the rotation of the bone to a particular axis angle in local or world space.
  35270. * @param axis The axis to rotate the bone on.
  35271. * @param angle The angle that the bone should be rotated to.
  35272. * @param space The space that the axis is in.
  35273. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35274. */
  35275. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  35276. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35277. var rotMat = BABYLON.Tmp.Matrix[0];
  35278. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  35279. var rotMatInv = BABYLON.Tmp.Matrix[1];
  35280. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  35281. rotMatInv.multiplyToRef(rotMat, rotMat);
  35282. this._rotateWithMatrix(rotMat, space, mesh);
  35283. };
  35284. /**
  35285. * Set the euler rotation of the bone in local of world space.
  35286. * @param rotation The euler rotation that the bone should be set to.
  35287. * @param space The space that the rotation is in.
  35288. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35289. */
  35290. Bone.prototype.setRotation = function (rotation, space, mesh) {
  35291. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35292. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  35293. };
  35294. /**
  35295. * Set the quaternion rotation of the bone in local of world space.
  35296. * @param quat The quaternion rotation that the bone should be set to.
  35297. * @param space The space that the rotation is in.
  35298. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35299. */
  35300. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  35301. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35302. var rotMatInv = BABYLON.Tmp.Matrix[0];
  35303. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  35304. var rotMat = BABYLON.Tmp.Matrix[1];
  35305. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  35306. rotMatInv.multiplyToRef(rotMat, rotMat);
  35307. this._rotateWithMatrix(rotMat, space, mesh);
  35308. };
  35309. /**
  35310. * Set the rotation matrix of the bone in local of world space.
  35311. * @param rotMat The rotation matrix that the bone should be set to.
  35312. * @param space The space that the rotation is in.
  35313. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35314. */
  35315. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  35316. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35317. var rotMatInv = BABYLON.Tmp.Matrix[0];
  35318. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  35319. var rotMat2 = BABYLON.Tmp.Matrix[1];
  35320. rotMat2.copyFrom(rotMat);
  35321. rotMatInv.multiplyToRef(rotMat, rotMat2);
  35322. this._rotateWithMatrix(rotMat2, space, mesh);
  35323. };
  35324. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  35325. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35326. var lmat = this.getLocalMatrix();
  35327. var lx = lmat.m[12];
  35328. var ly = lmat.m[13];
  35329. var lz = lmat.m[14];
  35330. var parent = this.getParent();
  35331. var parentScale = BABYLON.Tmp.Matrix[3];
  35332. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  35333. if (parent) {
  35334. if (space == BABYLON.Space.WORLD) {
  35335. if (mesh) {
  35336. parentScale.copyFrom(mesh.getWorldMatrix());
  35337. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  35338. }
  35339. else {
  35340. parentScale.copyFrom(parent.getAbsoluteTransform());
  35341. }
  35342. }
  35343. else {
  35344. parentScale = parent._scaleMatrix;
  35345. }
  35346. parentScaleInv.copyFrom(parentScale);
  35347. parentScaleInv.invert();
  35348. lmat.multiplyToRef(parentScale, lmat);
  35349. lmat.multiplyToRef(rmat, lmat);
  35350. lmat.multiplyToRef(parentScaleInv, lmat);
  35351. }
  35352. else {
  35353. if (space == BABYLON.Space.WORLD && mesh) {
  35354. parentScale.copyFrom(mesh.getWorldMatrix());
  35355. parentScaleInv.copyFrom(parentScale);
  35356. parentScaleInv.invert();
  35357. lmat.multiplyToRef(parentScale, lmat);
  35358. lmat.multiplyToRef(rmat, lmat);
  35359. lmat.multiplyToRef(parentScaleInv, lmat);
  35360. }
  35361. else {
  35362. lmat.multiplyToRef(rmat, lmat);
  35363. }
  35364. }
  35365. lmat.m[12] = lx;
  35366. lmat.m[13] = ly;
  35367. lmat.m[14] = lz;
  35368. this.computeAbsoluteTransforms();
  35369. this.markAsDirty();
  35370. };
  35371. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  35372. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35373. if (space == BABYLON.Space.WORLD) {
  35374. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  35375. scaleMatrix.copyFrom(this._scaleMatrix);
  35376. rotMatInv.copyFrom(this.getAbsoluteTransform());
  35377. if (mesh) {
  35378. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  35379. var meshScale = BABYLON.Tmp.Matrix[3];
  35380. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  35381. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  35382. }
  35383. rotMatInv.invert();
  35384. scaleMatrix.m[0] *= this._scalingDeterminant;
  35385. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  35386. }
  35387. else {
  35388. rotMatInv.copyFrom(this.getLocalMatrix());
  35389. rotMatInv.invert();
  35390. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  35391. scaleMatrix.copyFrom(this._scaleMatrix);
  35392. if (this._parent) {
  35393. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  35394. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  35395. pscaleMatrix.invert();
  35396. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  35397. }
  35398. else {
  35399. scaleMatrix.m[0] *= this._scalingDeterminant;
  35400. }
  35401. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  35402. }
  35403. };
  35404. /**
  35405. * Get the scale of the bone
  35406. * @returns the scale of the bone
  35407. */
  35408. Bone.prototype.getScale = function () {
  35409. return this._scaleVector.clone();
  35410. };
  35411. /**
  35412. * Copy the scale of the bone to a vector3.
  35413. * @param result The vector3 to copy the scale to
  35414. */
  35415. Bone.prototype.getScaleToRef = function (result) {
  35416. result.copyFrom(this._scaleVector);
  35417. };
  35418. /**
  35419. * Get the position of the bone in local or world space.
  35420. * @param space The space that the returned position is in.
  35421. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35422. * @returns The position of the bone
  35423. */
  35424. Bone.prototype.getPosition = function (space, mesh) {
  35425. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35426. var pos = BABYLON.Vector3.Zero();
  35427. this.getPositionToRef(space, mesh, pos);
  35428. return pos;
  35429. };
  35430. /**
  35431. * Copy the position of the bone to a vector3 in local or world space.
  35432. * @param space The space that the returned position is in.
  35433. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35434. * @param result The vector3 to copy the position to.
  35435. */
  35436. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  35437. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35438. if (space == BABYLON.Space.LOCAL) {
  35439. var lm = this.getLocalMatrix();
  35440. result.x = lm.m[12];
  35441. result.y = lm.m[13];
  35442. result.z = lm.m[14];
  35443. }
  35444. else {
  35445. var wm;
  35446. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  35447. if (mesh) {
  35448. wm = mesh.getWorldMatrix();
  35449. }
  35450. this._skeleton.computeAbsoluteTransforms();
  35451. var tmat = BABYLON.Tmp.Matrix[0];
  35452. if (mesh) {
  35453. tmat.copyFrom(this.getAbsoluteTransform());
  35454. tmat.multiplyToRef(wm, tmat);
  35455. }
  35456. else {
  35457. tmat = this.getAbsoluteTransform();
  35458. }
  35459. result.x = tmat.m[12];
  35460. result.y = tmat.m[13];
  35461. result.z = tmat.m[14];
  35462. }
  35463. };
  35464. /**
  35465. * Get the absolute position of the bone (world space).
  35466. * @param mesh The mesh that this bone is attached to.
  35467. * @returns The absolute position of the bone
  35468. */
  35469. Bone.prototype.getAbsolutePosition = function (mesh) {
  35470. var pos = BABYLON.Vector3.Zero();
  35471. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  35472. return pos;
  35473. };
  35474. /**
  35475. * Copy the absolute position of the bone (world space) to the result param.
  35476. * @param mesh The mesh that this bone is attached to.
  35477. * @param result The vector3 to copy the absolute position to.
  35478. */
  35479. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  35480. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  35481. };
  35482. /**
  35483. * Compute the absolute transforms of this bone and its children.
  35484. */
  35485. Bone.prototype.computeAbsoluteTransforms = function () {
  35486. if (this._parent) {
  35487. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  35488. }
  35489. else {
  35490. this._absoluteTransform.copyFrom(this._localMatrix);
  35491. var poseMatrix = this._skeleton.getPoseMatrix();
  35492. if (poseMatrix) {
  35493. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  35494. }
  35495. }
  35496. var children = this.children;
  35497. var len = children.length;
  35498. for (var i = 0; i < len; i++) {
  35499. children[i].computeAbsoluteTransforms();
  35500. }
  35501. };
  35502. Bone.prototype._syncScaleVector = function () {
  35503. var lm = this.getLocalMatrix();
  35504. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  35505. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  35506. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  35507. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  35508. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  35509. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  35510. this._scaleVector.x = xs * Math.sqrt(xsq);
  35511. this._scaleVector.y = ys * Math.sqrt(ysq);
  35512. this._scaleVector.z = zs * Math.sqrt(zsq);
  35513. if (this._parent) {
  35514. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  35515. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  35516. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  35517. }
  35518. 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);
  35519. };
  35520. /**
  35521. * Get the world direction from an axis that is in the local space of the bone.
  35522. * @param localAxis The local direction that is used to compute the world direction.
  35523. * @param mesh The mesh that this bone is attached to.
  35524. * @returns The world direction
  35525. */
  35526. Bone.prototype.getDirection = function (localAxis, mesh) {
  35527. var result = BABYLON.Vector3.Zero();
  35528. this.getDirectionToRef(localAxis, mesh, result);
  35529. return result;
  35530. };
  35531. /**
  35532. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  35533. * @param localAxis The local direction that is used to compute the world direction.
  35534. * @param mesh The mesh that this bone is attached to.
  35535. * @param result The vector3 that the world direction will be copied to.
  35536. */
  35537. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  35538. var wm;
  35539. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  35540. if (mesh) {
  35541. wm = mesh.getWorldMatrix();
  35542. }
  35543. this._skeleton.computeAbsoluteTransforms();
  35544. var mat = BABYLON.Tmp.Matrix[0];
  35545. mat.copyFrom(this.getAbsoluteTransform());
  35546. if (mesh) {
  35547. mat.multiplyToRef(wm, mat);
  35548. }
  35549. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  35550. result.normalize();
  35551. };
  35552. /**
  35553. * Get the euler rotation of the bone in local or world space.
  35554. * @param space The space that the rotation should be in.
  35555. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35556. * @returns The euler rotation
  35557. */
  35558. Bone.prototype.getRotation = function (space, mesh) {
  35559. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35560. var result = BABYLON.Vector3.Zero();
  35561. this.getRotationToRef(space, mesh, result);
  35562. return result;
  35563. };
  35564. /**
  35565. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  35566. * @param space The space that the rotation should be in.
  35567. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35568. * @param result The vector3 that the rotation should be copied to.
  35569. */
  35570. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  35571. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35572. var quat = BABYLON.Tmp.Quaternion[0];
  35573. this.getRotationQuaternionToRef(space, mesh, quat);
  35574. quat.toEulerAnglesToRef(result);
  35575. };
  35576. /**
  35577. * Get the quaternion rotation of the bone in either local or world space.
  35578. * @param space The space that the rotation should be in.
  35579. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35580. * @returns The quaternion rotation
  35581. */
  35582. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  35583. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35584. var result = BABYLON.Quaternion.Identity();
  35585. this.getRotationQuaternionToRef(space, mesh, result);
  35586. return result;
  35587. };
  35588. /**
  35589. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  35590. * @param space The space that the rotation should be in.
  35591. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35592. * @param result The quaternion that the rotation should be copied to.
  35593. */
  35594. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  35595. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35596. if (space == BABYLON.Space.LOCAL) {
  35597. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  35598. }
  35599. else {
  35600. var mat = BABYLON.Tmp.Matrix[0];
  35601. var amat = this.getAbsoluteTransform();
  35602. if (mesh) {
  35603. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  35604. }
  35605. else {
  35606. mat.copyFrom(amat);
  35607. }
  35608. mat.m[0] *= this._scalingDeterminant;
  35609. mat.m[1] *= this._scalingDeterminant;
  35610. mat.m[2] *= this._scalingDeterminant;
  35611. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  35612. }
  35613. };
  35614. /**
  35615. * Get the rotation matrix of the bone in local or world space.
  35616. * @param space The space that the rotation should be in.
  35617. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35618. * @returns The rotation matrix
  35619. */
  35620. Bone.prototype.getRotationMatrix = function (space, mesh) {
  35621. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35622. var result = BABYLON.Matrix.Identity();
  35623. this.getRotationMatrixToRef(space, mesh, result);
  35624. return result;
  35625. };
  35626. /**
  35627. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  35628. * @param space The space that the rotation should be in.
  35629. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35630. * @param result The quaternion that the rotation should be copied to.
  35631. */
  35632. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  35633. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35634. if (space == BABYLON.Space.LOCAL) {
  35635. this.getLocalMatrix().getRotationMatrixToRef(result);
  35636. }
  35637. else {
  35638. var mat = BABYLON.Tmp.Matrix[0];
  35639. var amat = this.getAbsoluteTransform();
  35640. if (mesh) {
  35641. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  35642. }
  35643. else {
  35644. mat.copyFrom(amat);
  35645. }
  35646. mat.m[0] *= this._scalingDeterminant;
  35647. mat.m[1] *= this._scalingDeterminant;
  35648. mat.m[2] *= this._scalingDeterminant;
  35649. mat.getRotationMatrixToRef(result);
  35650. }
  35651. };
  35652. /**
  35653. * Get the world position of a point that is in the local space of the bone.
  35654. * @param position The local position
  35655. * @param mesh The mesh that this bone is attached to.
  35656. * @returns The world position
  35657. */
  35658. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  35659. var result = BABYLON.Vector3.Zero();
  35660. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  35661. return result;
  35662. };
  35663. /**
  35664. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  35665. * @param position The local position
  35666. * @param mesh The mesh that this bone is attached to.
  35667. * @param result The vector3 that the world position should be copied to.
  35668. */
  35669. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  35670. var wm;
  35671. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  35672. if (mesh) {
  35673. wm = mesh.getWorldMatrix();
  35674. }
  35675. this._skeleton.computeAbsoluteTransforms();
  35676. var tmat = BABYLON.Tmp.Matrix[0];
  35677. if (mesh) {
  35678. tmat.copyFrom(this.getAbsoluteTransform());
  35679. tmat.multiplyToRef(wm, tmat);
  35680. }
  35681. else {
  35682. tmat = this.getAbsoluteTransform();
  35683. }
  35684. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  35685. };
  35686. /**
  35687. * Get the local position of a point that is in world space.
  35688. * @param position The world position
  35689. * @param mesh The mesh that this bone is attached to.
  35690. * @returns The local position
  35691. */
  35692. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  35693. var result = BABYLON.Vector3.Zero();
  35694. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  35695. return result;
  35696. };
  35697. /**
  35698. * Get the local position of a point that is in world space and copy it to the result param.
  35699. * @param position The world position
  35700. * @param mesh The mesh that this bone is attached to.
  35701. * @param result The vector3 that the local position should be copied to.
  35702. */
  35703. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  35704. var wm;
  35705. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  35706. if (mesh) {
  35707. wm = mesh.getWorldMatrix();
  35708. }
  35709. this._skeleton.computeAbsoluteTransforms();
  35710. var tmat = BABYLON.Tmp.Matrix[0];
  35711. tmat.copyFrom(this.getAbsoluteTransform());
  35712. if (mesh) {
  35713. tmat.multiplyToRef(wm, tmat);
  35714. }
  35715. tmat.invert();
  35716. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  35717. };
  35718. return Bone;
  35719. }(BABYLON.Node));
  35720. BABYLON.Bone = Bone;
  35721. })(BABYLON || (BABYLON = {}));
  35722. //# sourceMappingURL=babylon.bone.js.map
  35723. var BABYLON;
  35724. (function (BABYLON) {
  35725. var BoneIKController = (function () {
  35726. function BoneIKController(mesh, bone, options) {
  35727. this.targetPosition = BABYLON.Vector3.Zero();
  35728. this.poleTargetPosition = BABYLON.Vector3.Zero();
  35729. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  35730. this.poleAngle = 0;
  35731. this.slerpAmount = 1;
  35732. this._bone1Quat = BABYLON.Quaternion.Identity();
  35733. this._bone1Mat = BABYLON.Matrix.Identity();
  35734. this._bone2Ang = Math.PI;
  35735. this._maxAngle = Math.PI;
  35736. this._rightHandedSystem = false;
  35737. this._bendAxis = BABYLON.Vector3.Right();
  35738. this._slerping = false;
  35739. this._adjustRoll = 0;
  35740. this._bone2 = bone;
  35741. this._bone1 = bone.getParent();
  35742. this.mesh = mesh;
  35743. var bonePos = bone.getPosition();
  35744. if (bone.getAbsoluteTransform().determinant() > 0) {
  35745. this._rightHandedSystem = true;
  35746. this._bendAxis.x = 0;
  35747. this._bendAxis.y = 0;
  35748. this._bendAxis.z = -1;
  35749. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  35750. this._adjustRoll = Math.PI * .5;
  35751. this._bendAxis.z = 1;
  35752. }
  35753. }
  35754. if (this._bone1.length) {
  35755. var boneScale1 = this._bone1.getScale();
  35756. var boneScale2 = this._bone2.getScale();
  35757. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  35758. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  35759. }
  35760. else if (this._bone1.children[0]) {
  35761. mesh.computeWorldMatrix(true);
  35762. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  35763. var pos2 = this._bone2.getAbsolutePosition(mesh);
  35764. var pos3 = this._bone1.getAbsolutePosition(mesh);
  35765. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  35766. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  35767. }
  35768. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  35769. this.maxAngle = Math.PI;
  35770. if (options) {
  35771. if (options.targetMesh) {
  35772. this.targetMesh = options.targetMesh;
  35773. this.targetMesh.computeWorldMatrix(true);
  35774. }
  35775. if (options.poleTargetMesh) {
  35776. this.poleTargetMesh = options.poleTargetMesh;
  35777. this.poleTargetMesh.computeWorldMatrix(true);
  35778. }
  35779. else if (options.poleTargetBone) {
  35780. this.poleTargetBone = options.poleTargetBone;
  35781. }
  35782. else if (this._bone1.getParent()) {
  35783. this.poleTargetBone = this._bone1.getParent();
  35784. }
  35785. if (options.poleTargetLocalOffset) {
  35786. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  35787. }
  35788. if (options.poleAngle) {
  35789. this.poleAngle = options.poleAngle;
  35790. }
  35791. if (options.bendAxis) {
  35792. this._bendAxis.copyFrom(options.bendAxis);
  35793. }
  35794. if (options.maxAngle) {
  35795. this.maxAngle = options.maxAngle;
  35796. }
  35797. if (options.slerpAmount) {
  35798. this.slerpAmount = options.slerpAmount;
  35799. }
  35800. }
  35801. }
  35802. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  35803. get: function () {
  35804. return this._maxAngle;
  35805. },
  35806. set: function (value) {
  35807. this._setMaxAngle(value);
  35808. },
  35809. enumerable: true,
  35810. configurable: true
  35811. });
  35812. BoneIKController.prototype._setMaxAngle = function (ang) {
  35813. if (ang < 0) {
  35814. ang = 0;
  35815. }
  35816. if (ang > Math.PI || ang == undefined) {
  35817. ang = Math.PI;
  35818. }
  35819. this._maxAngle = ang;
  35820. var a = this._bone1Length;
  35821. var b = this._bone2Length;
  35822. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  35823. };
  35824. BoneIKController.prototype.update = function () {
  35825. var bone1 = this._bone1;
  35826. var target = this.targetPosition;
  35827. var poleTarget = this.poleTargetPosition;
  35828. var mat1 = BoneIKController._tmpMats[0];
  35829. var mat2 = BoneIKController._tmpMats[1];
  35830. if (this.targetMesh) {
  35831. target.copyFrom(this.targetMesh.getAbsolutePosition());
  35832. }
  35833. if (this.poleTargetBone) {
  35834. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  35835. }
  35836. else if (this.poleTargetMesh) {
  35837. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  35838. }
  35839. var bonePos = BoneIKController._tmpVecs[0];
  35840. var zaxis = BoneIKController._tmpVecs[1];
  35841. var xaxis = BoneIKController._tmpVecs[2];
  35842. var yaxis = BoneIKController._tmpVecs[3];
  35843. var upAxis = BoneIKController._tmpVecs[4];
  35844. var _tmpQuat = BoneIKController._tmpQuat;
  35845. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  35846. poleTarget.subtractToRef(bonePos, upAxis);
  35847. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  35848. upAxis.y = 1;
  35849. }
  35850. else {
  35851. upAxis.normalize();
  35852. }
  35853. target.subtractToRef(bonePos, yaxis);
  35854. yaxis.normalize();
  35855. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  35856. zaxis.normalize();
  35857. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  35858. xaxis.normalize();
  35859. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  35860. var a = this._bone1Length;
  35861. var b = this._bone2Length;
  35862. var c = BABYLON.Vector3.Distance(bonePos, target);
  35863. if (this._maxReach > 0) {
  35864. c = Math.min(this._maxReach, c);
  35865. }
  35866. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  35867. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  35868. if (acosa > 1) {
  35869. acosa = 1;
  35870. }
  35871. if (acosb > 1) {
  35872. acosb = 1;
  35873. }
  35874. if (acosa < -1) {
  35875. acosa = -1;
  35876. }
  35877. if (acosb < -1) {
  35878. acosb = -1;
  35879. }
  35880. var angA = Math.acos(acosa);
  35881. var angB = Math.acos(acosb);
  35882. var angC = -angA - angB;
  35883. if (this._rightHandedSystem) {
  35884. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  35885. mat2.multiplyToRef(mat1, mat1);
  35886. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  35887. mat2.multiplyToRef(mat1, mat1);
  35888. }
  35889. else {
  35890. var _tmpVec = BoneIKController._tmpVecs[5];
  35891. _tmpVec.copyFrom(this._bendAxis);
  35892. _tmpVec.x *= -1;
  35893. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  35894. mat2.multiplyToRef(mat1, mat1);
  35895. }
  35896. if (this.poleAngle) {
  35897. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  35898. mat1.multiplyToRef(mat2, mat1);
  35899. }
  35900. if (this.slerpAmount < 1) {
  35901. if (!this._slerping) {
  35902. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  35903. }
  35904. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  35905. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  35906. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  35907. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  35908. this._slerping = true;
  35909. }
  35910. else {
  35911. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  35912. this._bone1Mat.copyFrom(mat1);
  35913. this._slerping = false;
  35914. }
  35915. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  35916. this._bone2Ang = angC;
  35917. };
  35918. return BoneIKController;
  35919. }());
  35920. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  35921. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  35922. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  35923. BABYLON.BoneIKController = BoneIKController;
  35924. })(BABYLON || (BABYLON = {}));
  35925. //# sourceMappingURL=babylon.boneIKController.js.map
  35926. var BABYLON;
  35927. (function (BABYLON) {
  35928. var BoneLookController = (function () {
  35929. /**
  35930. * Create a BoneLookController
  35931. * @param mesh the mesh that the bone belongs to
  35932. * @param bone the bone that will be looking to the target
  35933. * @param target the target Vector3 to look at
  35934. * @param settings optional settings:
  35935. * - maxYaw: the maximum angle the bone will yaw to
  35936. * - minYaw: the minimum angle the bone will yaw to
  35937. * - maxPitch: the maximum angle the bone will pitch to
  35938. * - minPitch: the minimum angle the bone will yaw to
  35939. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  35940. * - upAxis: the up axis of the coordinate system
  35941. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  35942. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  35943. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  35944. * - adjustYaw: used to make an adjustment to the yaw of the bone
  35945. * - adjustPitch: used to make an adjustment to the pitch of the bone
  35946. * - adjustRoll: used to make an adjustment to the roll of the bone
  35947. **/
  35948. function BoneLookController(mesh, bone, target, options) {
  35949. /**
  35950. * The up axis of the coordinate system that is used when the bone is rotated.
  35951. */
  35952. this.upAxis = BABYLON.Vector3.Up();
  35953. /**
  35954. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  35955. */
  35956. this.upAxisSpace = BABYLON.Space.LOCAL;
  35957. /**
  35958. * Used to make an adjustment to the yaw of the bone.
  35959. */
  35960. this.adjustYaw = 0;
  35961. /**
  35962. * Used to make an adjustment to the pitch of the bone.
  35963. */
  35964. this.adjustPitch = 0;
  35965. /**
  35966. * Used to make an adjustment to the roll of the bone.
  35967. */
  35968. this.adjustRoll = 0;
  35969. /**
  35970. * 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).
  35971. */
  35972. this.slerpAmount = 1;
  35973. this._boneQuat = BABYLON.Quaternion.Identity();
  35974. this._slerping = false;
  35975. this._firstFrameSkipped = false;
  35976. this._fowardAxis = BABYLON.Vector3.Forward();
  35977. this.mesh = mesh;
  35978. this.bone = bone;
  35979. this.target = target;
  35980. if (options) {
  35981. if (options.adjustYaw) {
  35982. this.adjustYaw = options.adjustYaw;
  35983. }
  35984. if (options.adjustPitch) {
  35985. this.adjustPitch = options.adjustPitch;
  35986. }
  35987. if (options.adjustRoll) {
  35988. this.adjustRoll = options.adjustRoll;
  35989. }
  35990. if (options.maxYaw != null) {
  35991. this.maxYaw = options.maxYaw;
  35992. }
  35993. else {
  35994. this.maxYaw = Math.PI;
  35995. }
  35996. if (options.minYaw != null) {
  35997. this.minYaw = options.minYaw;
  35998. }
  35999. else {
  36000. this.minYaw = -Math.PI;
  36001. }
  36002. if (options.maxPitch != null) {
  36003. this.maxPitch = options.maxPitch;
  36004. }
  36005. else {
  36006. this.maxPitch = Math.PI;
  36007. }
  36008. if (options.minPitch != null) {
  36009. this.minPitch = options.minPitch;
  36010. }
  36011. else {
  36012. this.minPitch = -Math.PI;
  36013. }
  36014. if (options.slerpAmount != null) {
  36015. this.slerpAmount = options.slerpAmount;
  36016. }
  36017. if (options.upAxis != null) {
  36018. this.upAxis = options.upAxis;
  36019. }
  36020. if (options.upAxisSpace != null) {
  36021. this.upAxisSpace = options.upAxisSpace;
  36022. }
  36023. if (options.yawAxis != null || options.pitchAxis != null) {
  36024. var newYawAxis = BABYLON.Axis.Y;
  36025. var newPitchAxis = BABYLON.Axis.X;
  36026. if (options.yawAxis != null) {
  36027. newYawAxis = options.yawAxis.clone();
  36028. newYawAxis.normalize();
  36029. }
  36030. if (options.pitchAxis != null) {
  36031. newPitchAxis = options.pitchAxis.clone();
  36032. newPitchAxis.normalize();
  36033. }
  36034. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  36035. this._transformYawPitch = BABYLON.Matrix.Identity();
  36036. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  36037. this._transformYawPitchInv = this._transformYawPitch.clone();
  36038. this._transformYawPitch.invert();
  36039. }
  36040. }
  36041. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  36042. this.upAxisSpace = BABYLON.Space.LOCAL;
  36043. }
  36044. }
  36045. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  36046. /**
  36047. * Get/set the minimum yaw angle that the bone can look to.
  36048. */
  36049. get: function () {
  36050. return this._minYaw;
  36051. },
  36052. set: function (value) {
  36053. this._minYaw = value;
  36054. this._minYawSin = Math.sin(value);
  36055. this._minYawCos = Math.cos(value);
  36056. if (this._maxYaw != null) {
  36057. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  36058. this._yawRange = this._maxYaw - this._minYaw;
  36059. }
  36060. },
  36061. enumerable: true,
  36062. configurable: true
  36063. });
  36064. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  36065. /**
  36066. * Get/set the maximum yaw angle that the bone can look to.
  36067. */
  36068. get: function () {
  36069. return this._maxYaw;
  36070. },
  36071. set: function (value) {
  36072. this._maxYaw = value;
  36073. this._maxYawSin = Math.sin(value);
  36074. this._maxYawCos = Math.cos(value);
  36075. if (this._minYaw != null) {
  36076. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  36077. this._yawRange = this._maxYaw - this._minYaw;
  36078. }
  36079. },
  36080. enumerable: true,
  36081. configurable: true
  36082. });
  36083. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  36084. /**
  36085. * Get/set the minimum pitch angle that the bone can look to.
  36086. */
  36087. get: function () {
  36088. return this._minPitch;
  36089. },
  36090. set: function (value) {
  36091. this._minPitch = value;
  36092. this._minPitchTan = Math.tan(value);
  36093. },
  36094. enumerable: true,
  36095. configurable: true
  36096. });
  36097. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  36098. /**
  36099. * Get/set the maximum pitch angle that the bone can look to.
  36100. */
  36101. get: function () {
  36102. return this._maxPitch;
  36103. },
  36104. set: function (value) {
  36105. this._maxPitch = value;
  36106. this._maxPitchTan = Math.tan(value);
  36107. },
  36108. enumerable: true,
  36109. configurable: true
  36110. });
  36111. /**
  36112. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  36113. */
  36114. BoneLookController.prototype.update = function () {
  36115. //skip the first frame when slerping so that the mesh rotation is correct
  36116. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  36117. this._firstFrameSkipped = true;
  36118. return;
  36119. }
  36120. var bone = this.bone;
  36121. var bonePos = BoneLookController._tmpVecs[0];
  36122. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  36123. var target = this.target;
  36124. var _tmpMat1 = BoneLookController._tmpMats[0];
  36125. var _tmpMat2 = BoneLookController._tmpMats[1];
  36126. var mesh = this.mesh;
  36127. var parentBone = bone.getParent();
  36128. var upAxis = BoneLookController._tmpVecs[1];
  36129. upAxis.copyFrom(this.upAxis);
  36130. if (this.upAxisSpace == BABYLON.Space.BONE) {
  36131. if (this._transformYawPitch) {
  36132. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  36133. }
  36134. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  36135. }
  36136. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  36137. mesh.getDirectionToRef(upAxis, upAxis);
  36138. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  36139. upAxis.normalize();
  36140. }
  36141. }
  36142. var checkYaw = false;
  36143. var checkPitch = false;
  36144. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  36145. checkYaw = true;
  36146. }
  36147. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  36148. checkPitch = true;
  36149. }
  36150. if (checkYaw || checkPitch) {
  36151. var spaceMat = BoneLookController._tmpMats[2];
  36152. var spaceMatInv = BoneLookController._tmpMats[3];
  36153. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  36154. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  36155. }
  36156. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  36157. spaceMat.copyFrom(mesh.getWorldMatrix());
  36158. }
  36159. else {
  36160. var forwardAxis = BoneLookController._tmpVecs[2];
  36161. forwardAxis.copyFrom(this._fowardAxis);
  36162. if (this._transformYawPitch) {
  36163. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  36164. }
  36165. if (parentBone) {
  36166. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  36167. }
  36168. else {
  36169. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  36170. }
  36171. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  36172. rightAxis.normalize();
  36173. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  36174. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  36175. }
  36176. spaceMat.invertToRef(spaceMatInv);
  36177. var xzlen;
  36178. if (checkPitch) {
  36179. var localTarget = BoneLookController._tmpVecs[3];
  36180. target.subtractToRef(bonePos, localTarget);
  36181. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  36182. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  36183. var pitch = Math.atan2(localTarget.y, xzlen);
  36184. var newPitch = pitch;
  36185. if (pitch > this._maxPitch) {
  36186. localTarget.y = this._maxPitchTan * xzlen;
  36187. newPitch = this._maxPitch;
  36188. }
  36189. else if (pitch < this._minPitch) {
  36190. localTarget.y = this._minPitchTan * xzlen;
  36191. newPitch = this._minPitch;
  36192. }
  36193. if (pitch != newPitch) {
  36194. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  36195. localTarget.addInPlace(bonePos);
  36196. target = localTarget;
  36197. }
  36198. }
  36199. if (checkYaw) {
  36200. var localTarget = BoneLookController._tmpVecs[4];
  36201. target.subtractToRef(bonePos, localTarget);
  36202. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  36203. var yaw = Math.atan2(localTarget.x, localTarget.z);
  36204. var newYaw = yaw;
  36205. if (yaw > this._maxYaw || yaw < this._minYaw) {
  36206. if (xzlen == null) {
  36207. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  36208. }
  36209. if (this._yawRange > Math.PI) {
  36210. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  36211. localTarget.z = this._maxYawCos * xzlen;
  36212. localTarget.x = this._maxYawSin * xzlen;
  36213. newYaw = this._maxYaw;
  36214. }
  36215. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  36216. localTarget.z = this._minYawCos * xzlen;
  36217. localTarget.x = this._minYawSin * xzlen;
  36218. newYaw = this._minYaw;
  36219. }
  36220. }
  36221. else {
  36222. if (yaw > this._maxYaw) {
  36223. localTarget.z = this._maxYawCos * xzlen;
  36224. localTarget.x = this._maxYawSin * xzlen;
  36225. newYaw = this._maxYaw;
  36226. }
  36227. else if (yaw < this._minYaw) {
  36228. localTarget.z = this._minYawCos * xzlen;
  36229. localTarget.x = this._minYawSin * xzlen;
  36230. newYaw = this._minYaw;
  36231. }
  36232. }
  36233. }
  36234. if (this._slerping && this._yawRange > Math.PI) {
  36235. //are we going to be crossing into the min/max region?
  36236. var boneFwd = BoneLookController._tmpVecs[8];
  36237. boneFwd.copyFrom(BABYLON.Axis.Z);
  36238. if (this._transformYawPitch) {
  36239. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  36240. }
  36241. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  36242. this._boneQuat.toRotationMatrix(boneRotMat);
  36243. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  36244. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  36245. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  36246. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  36247. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  36248. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  36249. if (angBtwTar > angBtwMidYaw) {
  36250. if (xzlen == null) {
  36251. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  36252. }
  36253. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  36254. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  36255. if (angBtwMin < angBtwMax) {
  36256. newYaw = boneYaw + Math.PI * .75;
  36257. localTarget.z = Math.cos(newYaw) * xzlen;
  36258. localTarget.x = Math.sin(newYaw) * xzlen;
  36259. }
  36260. else {
  36261. newYaw = boneYaw - Math.PI * .75;
  36262. localTarget.z = Math.cos(newYaw) * xzlen;
  36263. localTarget.x = Math.sin(newYaw) * xzlen;
  36264. }
  36265. }
  36266. }
  36267. if (yaw != newYaw) {
  36268. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  36269. localTarget.addInPlace(bonePos);
  36270. target = localTarget;
  36271. }
  36272. }
  36273. }
  36274. var zaxis = BoneLookController._tmpVecs[5];
  36275. var xaxis = BoneLookController._tmpVecs[6];
  36276. var yaxis = BoneLookController._tmpVecs[7];
  36277. var _tmpQuat = BoneLookController._tmpQuat;
  36278. target.subtractToRef(bonePos, zaxis);
  36279. zaxis.normalize();
  36280. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  36281. xaxis.normalize();
  36282. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  36283. yaxis.normalize();
  36284. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  36285. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  36286. return;
  36287. }
  36288. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  36289. return;
  36290. }
  36291. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  36292. return;
  36293. }
  36294. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  36295. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  36296. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  36297. }
  36298. if (this.slerpAmount < 1) {
  36299. if (!this._slerping) {
  36300. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  36301. }
  36302. if (this._transformYawPitch) {
  36303. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  36304. }
  36305. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  36306. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  36307. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  36308. this._slerping = true;
  36309. }
  36310. else {
  36311. if (this._transformYawPitch) {
  36312. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  36313. }
  36314. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  36315. this._slerping = false;
  36316. }
  36317. };
  36318. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  36319. var angDiff = ang2 - ang1;
  36320. angDiff %= Math.PI * 2;
  36321. if (angDiff > Math.PI) {
  36322. angDiff -= Math.PI * 2;
  36323. }
  36324. else if (angDiff < -Math.PI) {
  36325. angDiff += Math.PI * 2;
  36326. }
  36327. return angDiff;
  36328. };
  36329. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  36330. ang1 %= (2 * Math.PI);
  36331. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  36332. ang2 %= (2 * Math.PI);
  36333. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  36334. var ab = 0;
  36335. if (ang1 < ang2) {
  36336. ab = ang2 - ang1;
  36337. }
  36338. else {
  36339. ab = ang1 - ang2;
  36340. }
  36341. if (ab > Math.PI) {
  36342. ab = Math.PI * 2 - ab;
  36343. }
  36344. return ab;
  36345. };
  36346. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  36347. ang %= (2 * Math.PI);
  36348. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  36349. ang1 %= (2 * Math.PI);
  36350. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  36351. ang2 %= (2 * Math.PI);
  36352. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  36353. if (ang1 < ang2) {
  36354. if (ang > ang1 && ang < ang2) {
  36355. return true;
  36356. }
  36357. }
  36358. else {
  36359. if (ang > ang2 && ang < ang1) {
  36360. return true;
  36361. }
  36362. }
  36363. return false;
  36364. };
  36365. return BoneLookController;
  36366. }());
  36367. 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()];
  36368. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  36369. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  36370. BABYLON.BoneLookController = BoneLookController;
  36371. })(BABYLON || (BABYLON = {}));
  36372. //# sourceMappingURL=babylon.boneLookController.js.map
  36373. var BABYLON;
  36374. (function (BABYLON) {
  36375. var Skeleton = (function () {
  36376. function Skeleton(name, id, scene) {
  36377. this.name = name;
  36378. this.id = id;
  36379. this.bones = new Array();
  36380. this.needInitialSkinMatrix = false;
  36381. this._isDirty = true;
  36382. this._meshesWithPoseMatrix = new Array();
  36383. this._identity = BABYLON.Matrix.Identity();
  36384. this._ranges = {};
  36385. this._lastAbsoluteTransformsUpdateId = -1;
  36386. // Events
  36387. /**
  36388. * An event triggered before computing the skeleton's matrices
  36389. * @type {BABYLON.Observable}
  36390. */
  36391. this.onBeforeComputeObservable = new BABYLON.Observable();
  36392. this.bones = [];
  36393. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36394. scene.skeletons.push(this);
  36395. //make sure it will recalculate the matrix next time prepare is called.
  36396. this._isDirty = true;
  36397. }
  36398. // Members
  36399. Skeleton.prototype.getTransformMatrices = function (mesh) {
  36400. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  36401. return mesh._bonesTransformMatrices;
  36402. }
  36403. if (!this._transformMatrices) {
  36404. this.prepare();
  36405. }
  36406. return this._transformMatrices;
  36407. };
  36408. Skeleton.prototype.getScene = function () {
  36409. return this._scene;
  36410. };
  36411. // Methods
  36412. /**
  36413. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  36414. */
  36415. Skeleton.prototype.toString = function (fullDetails) {
  36416. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  36417. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  36418. if (fullDetails) {
  36419. ret += ", Ranges: {";
  36420. var first = true;
  36421. for (var name_1 in this._ranges) {
  36422. if (first) {
  36423. ret += ", ";
  36424. first = false;
  36425. }
  36426. ret += name_1;
  36427. }
  36428. ret += "}";
  36429. }
  36430. return ret;
  36431. };
  36432. /**
  36433. * Get bone's index searching by name
  36434. * @param {string} name is bone's name to search for
  36435. * @return {number} Indice of the bone. Returns -1 if not found
  36436. */
  36437. Skeleton.prototype.getBoneIndexByName = function (name) {
  36438. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  36439. if (this.bones[boneIndex].name === name) {
  36440. return boneIndex;
  36441. }
  36442. }
  36443. return -1;
  36444. };
  36445. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  36446. // check name not already in use
  36447. if (!this._ranges[name]) {
  36448. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  36449. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  36450. if (this.bones[i].animations[0]) {
  36451. this.bones[i].animations[0].createRange(name, from, to);
  36452. }
  36453. }
  36454. }
  36455. };
  36456. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  36457. if (deleteFrames === void 0) { deleteFrames = true; }
  36458. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  36459. if (this.bones[i].animations[0]) {
  36460. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  36461. }
  36462. }
  36463. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  36464. };
  36465. Skeleton.prototype.getAnimationRange = function (name) {
  36466. return this._ranges[name];
  36467. };
  36468. /**
  36469. * Returns as an Array, all AnimationRanges defined on this skeleton
  36470. */
  36471. Skeleton.prototype.getAnimationRanges = function () {
  36472. var animationRanges = [];
  36473. var name;
  36474. var i = 0;
  36475. for (name in this._ranges) {
  36476. animationRanges[i] = this._ranges[name];
  36477. i++;
  36478. }
  36479. return animationRanges;
  36480. };
  36481. /**
  36482. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  36483. */
  36484. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  36485. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  36486. if (this._ranges[name] || !source.getAnimationRange(name)) {
  36487. return false;
  36488. }
  36489. var ret = true;
  36490. var frameOffset = this._getHighestAnimationFrame() + 1;
  36491. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  36492. var boneDict = {};
  36493. var sourceBones = source.bones;
  36494. var nBones;
  36495. var i;
  36496. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  36497. boneDict[sourceBones[i].name] = sourceBones[i];
  36498. }
  36499. if (this.bones.length !== sourceBones.length) {
  36500. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  36501. ret = false;
  36502. }
  36503. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  36504. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  36505. var boneName = this.bones[i].name;
  36506. var sourceBone = boneDict[boneName];
  36507. if (sourceBone) {
  36508. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  36509. }
  36510. else {
  36511. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  36512. ret = false;
  36513. }
  36514. }
  36515. // do not call createAnimationRange(), since it also is done to bones, which was already done
  36516. var range = source.getAnimationRange(name);
  36517. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  36518. return ret;
  36519. };
  36520. Skeleton.prototype.returnToRest = function () {
  36521. for (var index = 0; index < this.bones.length; index++) {
  36522. this.bones[index].returnToRest();
  36523. }
  36524. };
  36525. Skeleton.prototype._getHighestAnimationFrame = function () {
  36526. var ret = 0;
  36527. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  36528. if (this.bones[i].animations[0]) {
  36529. var highest = this.bones[i].animations[0].getHighestFrame();
  36530. if (ret < highest) {
  36531. ret = highest;
  36532. }
  36533. }
  36534. }
  36535. return ret;
  36536. };
  36537. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  36538. var range = this.getAnimationRange(name);
  36539. if (!range) {
  36540. return null;
  36541. }
  36542. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  36543. };
  36544. Skeleton.prototype._markAsDirty = function () {
  36545. this._isDirty = true;
  36546. };
  36547. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  36548. this._meshesWithPoseMatrix.push(mesh);
  36549. };
  36550. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  36551. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  36552. if (index > -1) {
  36553. this._meshesWithPoseMatrix.splice(index, 1);
  36554. }
  36555. };
  36556. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  36557. this.onBeforeComputeObservable.notifyObservers(this);
  36558. for (var index = 0; index < this.bones.length; index++) {
  36559. var bone = this.bones[index];
  36560. var parentBone = bone.getParent();
  36561. if (parentBone) {
  36562. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  36563. }
  36564. else {
  36565. if (initialSkinMatrix) {
  36566. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  36567. }
  36568. else {
  36569. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  36570. }
  36571. }
  36572. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  36573. }
  36574. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  36575. };
  36576. Skeleton.prototype.prepare = function () {
  36577. if (!this._isDirty) {
  36578. return;
  36579. }
  36580. if (this.needInitialSkinMatrix) {
  36581. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  36582. var mesh = this._meshesWithPoseMatrix[index];
  36583. var poseMatrix = mesh.getPoseMatrix();
  36584. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  36585. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  36586. }
  36587. if (this._synchronizedWithMesh !== mesh) {
  36588. this._synchronizedWithMesh = mesh;
  36589. // Prepare bones
  36590. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  36591. var bone = this.bones[boneIndex];
  36592. if (!bone.getParent()) {
  36593. var matrix = bone.getBaseMatrix();
  36594. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  36595. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  36596. }
  36597. }
  36598. }
  36599. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  36600. }
  36601. }
  36602. else {
  36603. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  36604. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  36605. }
  36606. this._computeTransformMatrices(this._transformMatrices, null);
  36607. }
  36608. this._isDirty = false;
  36609. this._scene._activeBones.addCount(this.bones.length, false);
  36610. };
  36611. Skeleton.prototype.getAnimatables = function () {
  36612. if (!this._animatables || this._animatables.length !== this.bones.length) {
  36613. this._animatables = [];
  36614. for (var index = 0; index < this.bones.length; index++) {
  36615. this._animatables.push(this.bones[index]);
  36616. }
  36617. }
  36618. return this._animatables;
  36619. };
  36620. Skeleton.prototype.clone = function (name, id) {
  36621. var result = new Skeleton(name, id || name, this._scene);
  36622. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  36623. for (var index = 0; index < this.bones.length; index++) {
  36624. var source = this.bones[index];
  36625. var parentBone = null;
  36626. if (source.getParent()) {
  36627. var parentIndex = this.bones.indexOf(source.getParent());
  36628. parentBone = result.bones[parentIndex];
  36629. }
  36630. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  36631. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  36632. }
  36633. if (this._ranges) {
  36634. result._ranges = {};
  36635. for (var rangeName in this._ranges) {
  36636. result._ranges[rangeName] = this._ranges[rangeName].clone();
  36637. }
  36638. }
  36639. this._isDirty = true;
  36640. return result;
  36641. };
  36642. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  36643. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  36644. this.bones.forEach(function (bone) {
  36645. bone.animations.forEach(function (animation) {
  36646. animation.enableBlending = true;
  36647. animation.blendingSpeed = blendingSpeed;
  36648. });
  36649. });
  36650. };
  36651. Skeleton.prototype.dispose = function () {
  36652. this._meshesWithPoseMatrix = [];
  36653. // Animations
  36654. this.getScene().stopAnimation(this);
  36655. // Remove from scene
  36656. this.getScene().removeSkeleton(this);
  36657. };
  36658. Skeleton.prototype.serialize = function () {
  36659. var serializationObject = {};
  36660. serializationObject.name = this.name;
  36661. serializationObject.id = this.id;
  36662. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  36663. serializationObject.bones = [];
  36664. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  36665. for (var index = 0; index < this.bones.length; index++) {
  36666. var bone = this.bones[index];
  36667. var serializedBone = {
  36668. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  36669. name: bone.name,
  36670. matrix: bone.getBaseMatrix().toArray(),
  36671. rest: bone.getRestPose().toArray()
  36672. };
  36673. serializationObject.bones.push(serializedBone);
  36674. if (bone.length) {
  36675. serializedBone.length = bone.length;
  36676. }
  36677. if (bone.animations && bone.animations.length > 0) {
  36678. serializedBone.animation = bone.animations[0].serialize();
  36679. }
  36680. serializationObject.ranges = [];
  36681. for (var name in this._ranges) {
  36682. var range = {};
  36683. range.name = name;
  36684. range.from = this._ranges[name].from;
  36685. range.to = this._ranges[name].to;
  36686. serializationObject.ranges.push(range);
  36687. }
  36688. }
  36689. return serializationObject;
  36690. };
  36691. Skeleton.Parse = function (parsedSkeleton, scene) {
  36692. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  36693. if (parsedSkeleton.dimensionsAtRest) {
  36694. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  36695. }
  36696. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  36697. var index;
  36698. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  36699. var parsedBone = parsedSkeleton.bones[index];
  36700. var parentBone = null;
  36701. if (parsedBone.parentBoneIndex > -1) {
  36702. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  36703. }
  36704. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  36705. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  36706. if (parsedBone.length) {
  36707. bone.length = parsedBone.length;
  36708. }
  36709. if (parsedBone.animation) {
  36710. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  36711. }
  36712. }
  36713. // placed after bones, so createAnimationRange can cascade down
  36714. if (parsedSkeleton.ranges) {
  36715. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  36716. var data = parsedSkeleton.ranges[index];
  36717. skeleton.createAnimationRange(data.name, data.from, data.to);
  36718. }
  36719. }
  36720. return skeleton;
  36721. };
  36722. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  36723. if (forceUpdate === void 0) { forceUpdate = false; }
  36724. var renderId = this._scene.getRenderId();
  36725. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  36726. this.bones[0].computeAbsoluteTransforms();
  36727. this._lastAbsoluteTransformsUpdateId = renderId;
  36728. }
  36729. };
  36730. Skeleton.prototype.getPoseMatrix = function () {
  36731. var poseMatrix;
  36732. if (this._meshesWithPoseMatrix.length > 0) {
  36733. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  36734. }
  36735. return poseMatrix;
  36736. };
  36737. return Skeleton;
  36738. }());
  36739. BABYLON.Skeleton = Skeleton;
  36740. })(BABYLON || (BABYLON = {}));
  36741. //# sourceMappingURL=babylon.skeleton.js.map
  36742. var BABYLON;
  36743. (function (BABYLON) {
  36744. var PostProcess = (function () {
  36745. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  36746. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  36747. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  36748. this.name = name;
  36749. this.width = -1;
  36750. this.height = -1;
  36751. /*
  36752. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  36753. Can only be used on a single postprocess or on the last one of a chain.
  36754. */
  36755. this.enablePixelPerfectMode = false;
  36756. this.samples = 1;
  36757. this._reusable = false;
  36758. this._textures = new BABYLON.SmartArray(2);
  36759. this._currentRenderTextureInd = 0;
  36760. this._scaleRatio = new BABYLON.Vector2(1, 1);
  36761. // Events
  36762. /**
  36763. * An event triggered when the postprocess is activated.
  36764. * @type {BABYLON.Observable}
  36765. */
  36766. this.onActivateObservable = new BABYLON.Observable();
  36767. /**
  36768. * An event triggered when the postprocess changes its size.
  36769. * @type {BABYLON.Observable}
  36770. */
  36771. this.onSizeChangedObservable = new BABYLON.Observable();
  36772. /**
  36773. * An event triggered when the postprocess applies its effect.
  36774. * @type {BABYLON.Observable}
  36775. */
  36776. this.onApplyObservable = new BABYLON.Observable();
  36777. /**
  36778. * An event triggered before rendering the postprocess
  36779. * @type {BABYLON.Observable}
  36780. */
  36781. this.onBeforeRenderObservable = new BABYLON.Observable();
  36782. /**
  36783. * An event triggered after rendering the postprocess
  36784. * @type {BABYLON.Observable}
  36785. */
  36786. this.onAfterRenderObservable = new BABYLON.Observable();
  36787. if (camera != null) {
  36788. this._camera = camera;
  36789. this._scene = camera.getScene();
  36790. camera.attachPostProcess(this);
  36791. this._engine = this._scene.getEngine();
  36792. }
  36793. else {
  36794. this._engine = engine;
  36795. }
  36796. this._options = options;
  36797. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  36798. this._reusable = reusable || false;
  36799. this._textureType = textureType;
  36800. this._samplers = samplers || [];
  36801. this._samplers.push("textureSampler");
  36802. this._fragmentUrl = fragmentUrl;
  36803. this._parameters = parameters || [];
  36804. this._parameters.push("scale");
  36805. this.updateEffect(defines);
  36806. }
  36807. Object.defineProperty(PostProcess.prototype, "onActivate", {
  36808. set: function (callback) {
  36809. if (this._onActivateObserver) {
  36810. this.onActivateObservable.remove(this._onActivateObserver);
  36811. }
  36812. this._onActivateObserver = this.onActivateObservable.add(callback);
  36813. },
  36814. enumerable: true,
  36815. configurable: true
  36816. });
  36817. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  36818. set: function (callback) {
  36819. if (this._onSizeChangedObserver) {
  36820. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  36821. }
  36822. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  36823. },
  36824. enumerable: true,
  36825. configurable: true
  36826. });
  36827. Object.defineProperty(PostProcess.prototype, "onApply", {
  36828. set: function (callback) {
  36829. if (this._onApplyObserver) {
  36830. this.onApplyObservable.remove(this._onApplyObserver);
  36831. }
  36832. this._onApplyObserver = this.onApplyObservable.add(callback);
  36833. },
  36834. enumerable: true,
  36835. configurable: true
  36836. });
  36837. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  36838. set: function (callback) {
  36839. if (this._onBeforeRenderObserver) {
  36840. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  36841. }
  36842. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  36843. },
  36844. enumerable: true,
  36845. configurable: true
  36846. });
  36847. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  36848. set: function (callback) {
  36849. if (this._onAfterRenderObserver) {
  36850. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  36851. }
  36852. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  36853. },
  36854. enumerable: true,
  36855. configurable: true
  36856. });
  36857. PostProcess.prototype.updateEffect = function (defines) {
  36858. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  36859. };
  36860. PostProcess.prototype.isReusable = function () {
  36861. return this._reusable;
  36862. };
  36863. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  36864. PostProcess.prototype.markTextureDirty = function () {
  36865. this.width = -1;
  36866. };
  36867. PostProcess.prototype.activate = function (camera, sourceTexture) {
  36868. var _this = this;
  36869. camera = camera || this._camera;
  36870. var scene = camera.getScene();
  36871. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  36872. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  36873. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  36874. var desiredWidth = this._options.width || requiredWidth;
  36875. var desiredHeight = this._options.height || requiredHeight;
  36876. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  36877. if (!this._options.width) {
  36878. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  36879. }
  36880. if (!this._options.height) {
  36881. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  36882. }
  36883. }
  36884. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  36885. if (this._textures.length > 0) {
  36886. for (var i = 0; i < this._textures.length; i++) {
  36887. this._engine._releaseTexture(this._textures.data[i]);
  36888. }
  36889. this._textures.reset();
  36890. }
  36891. this.width = desiredWidth;
  36892. this.height = desiredHeight;
  36893. var textureSize = { width: this.width, height: this.height };
  36894. var textureOptions = {
  36895. generateMipMaps: false,
  36896. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  36897. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  36898. samplingMode: this.renderTargetSamplingMode,
  36899. type: this._textureType
  36900. };
  36901. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  36902. if (this._reusable) {
  36903. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  36904. }
  36905. this.onSizeChangedObservable.notifyObservers(this);
  36906. }
  36907. this._textures.forEach(function (texture) {
  36908. if (texture.samples !== _this.samples) {
  36909. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  36910. }
  36911. });
  36912. if (this.enablePixelPerfectMode) {
  36913. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  36914. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  36915. }
  36916. else {
  36917. this._scaleRatio.copyFromFloats(1, 1);
  36918. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  36919. }
  36920. this.onActivateObservable.notifyObservers(camera);
  36921. // Clear
  36922. if (this.clearColor) {
  36923. this._engine.clear(this.clearColor, true, true, true);
  36924. }
  36925. else {
  36926. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  36927. }
  36928. if (this._reusable) {
  36929. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  36930. }
  36931. };
  36932. Object.defineProperty(PostProcess.prototype, "isSupported", {
  36933. get: function () {
  36934. return this._effect.isSupported;
  36935. },
  36936. enumerable: true,
  36937. configurable: true
  36938. });
  36939. PostProcess.prototype.apply = function () {
  36940. // Check
  36941. if (!this._effect.isReady())
  36942. return null;
  36943. // States
  36944. this._engine.enableEffect(this._effect);
  36945. this._engine.setState(false);
  36946. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36947. this._engine.setDepthBuffer(false);
  36948. this._engine.setDepthWrite(false);
  36949. // Texture
  36950. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  36951. // Parameters
  36952. this._effect.setVector2("scale", this._scaleRatio);
  36953. this.onApplyObservable.notifyObservers(this._effect);
  36954. return this._effect;
  36955. };
  36956. PostProcess.prototype.dispose = function (camera) {
  36957. camera = camera || this._camera;
  36958. if (this._textures.length > 0) {
  36959. for (var i = 0; i < this._textures.length; i++) {
  36960. this._engine._releaseTexture(this._textures.data[i]);
  36961. }
  36962. }
  36963. this._textures.dispose();
  36964. if (!camera) {
  36965. return;
  36966. }
  36967. camera.detachPostProcess(this);
  36968. var index = camera._postProcesses.indexOf(this);
  36969. if (index === 0 && camera._postProcesses.length > 0) {
  36970. this._camera._postProcesses[0].markTextureDirty();
  36971. }
  36972. this.onActivateObservable.clear();
  36973. this.onAfterRenderObservable.clear();
  36974. this.onApplyObservable.clear();
  36975. this.onBeforeRenderObservable.clear();
  36976. this.onSizeChangedObservable.clear();
  36977. };
  36978. return PostProcess;
  36979. }());
  36980. BABYLON.PostProcess = PostProcess;
  36981. })(BABYLON || (BABYLON = {}));
  36982. //# sourceMappingURL=babylon.postProcess.js.map
  36983. var BABYLON;
  36984. (function (BABYLON) {
  36985. var PostProcessManager = (function () {
  36986. function PostProcessManager(scene) {
  36987. this._vertexBuffers = {};
  36988. this._scene = scene;
  36989. }
  36990. PostProcessManager.prototype._prepareBuffers = function () {
  36991. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36992. return;
  36993. }
  36994. // VBO
  36995. var vertices = [];
  36996. vertices.push(1, 1);
  36997. vertices.push(-1, 1);
  36998. vertices.push(-1, -1);
  36999. vertices.push(1, -1);
  37000. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37001. // Indices
  37002. var indices = [];
  37003. indices.push(0);
  37004. indices.push(1);
  37005. indices.push(2);
  37006. indices.push(0);
  37007. indices.push(2);
  37008. indices.push(3);
  37009. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37010. };
  37011. // Methods
  37012. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  37013. var postProcesses = this._scene.activeCamera._postProcesses;
  37014. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37015. return false;
  37016. }
  37017. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  37018. return true;
  37019. };
  37020. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  37021. var engine = this._scene.getEngine();
  37022. for (var index = 0; index < postProcesses.length; index++) {
  37023. if (index < postProcesses.length - 1) {
  37024. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37025. }
  37026. else {
  37027. if (targetTexture) {
  37028. engine.bindFramebuffer(targetTexture);
  37029. }
  37030. else {
  37031. engine.restoreDefaultFramebuffer();
  37032. }
  37033. }
  37034. var pp = postProcesses[index];
  37035. var effect = pp.apply();
  37036. if (effect) {
  37037. pp.onBeforeRenderObservable.notifyObservers(effect);
  37038. // VBOs
  37039. this._prepareBuffers();
  37040. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37041. // Draw order
  37042. engine.draw(true, 0, 6);
  37043. pp.onAfterRenderObservable.notifyObservers(effect);
  37044. }
  37045. }
  37046. // Restore depth buffer
  37047. engine.setDepthBuffer(true);
  37048. engine.setDepthWrite(true);
  37049. };
  37050. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  37051. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  37052. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37053. return;
  37054. }
  37055. var engine = this._scene.getEngine();
  37056. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37057. if (index < len - 1) {
  37058. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37059. }
  37060. else {
  37061. if (targetTexture) {
  37062. engine.bindFramebuffer(targetTexture, faceIndex);
  37063. }
  37064. else {
  37065. engine.restoreDefaultFramebuffer();
  37066. }
  37067. }
  37068. if (doNotPresent) {
  37069. break;
  37070. }
  37071. var pp = postProcesses[index];
  37072. var effect = pp.apply();
  37073. if (effect) {
  37074. pp.onBeforeRenderObservable.notifyObservers(effect);
  37075. // VBOs
  37076. this._prepareBuffers();
  37077. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37078. // Draw order
  37079. engine.draw(true, 0, 6);
  37080. pp.onAfterRenderObservable.notifyObservers(effect);
  37081. }
  37082. }
  37083. // Restore depth buffer
  37084. engine.setDepthBuffer(true);
  37085. engine.setDepthWrite(true);
  37086. };
  37087. PostProcessManager.prototype.dispose = function () {
  37088. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37089. if (buffer) {
  37090. buffer.dispose();
  37091. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37092. }
  37093. if (this._indexBuffer) {
  37094. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37095. this._indexBuffer = null;
  37096. }
  37097. };
  37098. return PostProcessManager;
  37099. }());
  37100. BABYLON.PostProcessManager = PostProcessManager;
  37101. })(BABYLON || (BABYLON = {}));
  37102. //# sourceMappingURL=babylon.postProcessManager.js.map
  37103. var BABYLON;
  37104. (function (BABYLON) {
  37105. var PassPostProcess = (function (_super) {
  37106. __extends(PassPostProcess, _super);
  37107. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  37108. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  37109. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  37110. }
  37111. return PassPostProcess;
  37112. }(BABYLON.PostProcess));
  37113. BABYLON.PassPostProcess = PassPostProcess;
  37114. })(BABYLON || (BABYLON = {}));
  37115. //# sourceMappingURL=babylon.passPostProcess.js.map
  37116. var BABYLON;
  37117. (function (BABYLON) {
  37118. /**
  37119. * This is a holder class for the physics joint created by the physics plugin.
  37120. * It holds a set of functions to control the underlying joint.
  37121. */
  37122. var PhysicsJoint = (function () {
  37123. function PhysicsJoint(type, jointData) {
  37124. this.type = type;
  37125. this.jointData = jointData;
  37126. jointData.nativeParams = jointData.nativeParams || {};
  37127. }
  37128. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  37129. get: function () {
  37130. return this._physicsJoint;
  37131. },
  37132. set: function (newJoint) {
  37133. if (this._physicsJoint) {
  37134. //remove from the wolrd
  37135. }
  37136. this._physicsJoint = newJoint;
  37137. },
  37138. enumerable: true,
  37139. configurable: true
  37140. });
  37141. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  37142. set: function (physicsPlugin) {
  37143. this._physicsPlugin = physicsPlugin;
  37144. },
  37145. enumerable: true,
  37146. configurable: true
  37147. });
  37148. /**
  37149. * Execute a function that is physics-plugin specific.
  37150. * @param {Function} func the function that will be executed.
  37151. * It accepts two parameters: the physics world and the physics joint.
  37152. */
  37153. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  37154. func(this._physicsPlugin.world, this._physicsJoint);
  37155. };
  37156. return PhysicsJoint;
  37157. }());
  37158. //TODO check if the native joints are the same
  37159. //Joint Types
  37160. PhysicsJoint.DistanceJoint = 0;
  37161. PhysicsJoint.HingeJoint = 1;
  37162. PhysicsJoint.BallAndSocketJoint = 2;
  37163. PhysicsJoint.WheelJoint = 3;
  37164. PhysicsJoint.SliderJoint = 4;
  37165. //OIMO
  37166. PhysicsJoint.PrismaticJoint = 5;
  37167. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  37168. PhysicsJoint.UniversalJoint = 6;
  37169. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  37170. //Cannon
  37171. //Similar to a Ball-Joint. Different in params
  37172. PhysicsJoint.PointToPointJoint = 8;
  37173. //Cannon only at the moment
  37174. PhysicsJoint.SpringJoint = 9;
  37175. PhysicsJoint.LockJoint = 10;
  37176. BABYLON.PhysicsJoint = PhysicsJoint;
  37177. /**
  37178. * A class representing a physics distance joint.
  37179. */
  37180. var DistanceJoint = (function (_super) {
  37181. __extends(DistanceJoint, _super);
  37182. function DistanceJoint(jointData) {
  37183. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  37184. }
  37185. /**
  37186. * Update the predefined distance.
  37187. */
  37188. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  37189. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  37190. };
  37191. return DistanceJoint;
  37192. }(PhysicsJoint));
  37193. BABYLON.DistanceJoint = DistanceJoint;
  37194. var MotorEnabledJoint = (function (_super) {
  37195. __extends(MotorEnabledJoint, _super);
  37196. function MotorEnabledJoint(type, jointData) {
  37197. return _super.call(this, type, jointData) || this;
  37198. }
  37199. /**
  37200. * Set the motor values.
  37201. * Attention, this function is plugin specific. Engines won't react 100% the same.
  37202. * @param {number} force the force to apply
  37203. * @param {number} maxForce max force for this motor.
  37204. */
  37205. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  37206. this._physicsPlugin.setMotor(this, force, maxForce);
  37207. };
  37208. /**
  37209. * Set the motor's limits.
  37210. * Attention, this function is plugin specific. Engines won't react 100% the same.
  37211. */
  37212. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  37213. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  37214. };
  37215. return MotorEnabledJoint;
  37216. }(PhysicsJoint));
  37217. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  37218. /**
  37219. * This class represents a single hinge physics joint
  37220. */
  37221. var HingeJoint = (function (_super) {
  37222. __extends(HingeJoint, _super);
  37223. function HingeJoint(jointData) {
  37224. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  37225. }
  37226. /**
  37227. * Set the motor values.
  37228. * Attention, this function is plugin specific. Engines won't react 100% the same.
  37229. * @param {number} force the force to apply
  37230. * @param {number} maxForce max force for this motor.
  37231. */
  37232. HingeJoint.prototype.setMotor = function (force, maxForce) {
  37233. this._physicsPlugin.setMotor(this, force, maxForce);
  37234. };
  37235. /**
  37236. * Set the motor's limits.
  37237. * Attention, this function is plugin specific. Engines won't react 100% the same.
  37238. */
  37239. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  37240. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  37241. };
  37242. return HingeJoint;
  37243. }(MotorEnabledJoint));
  37244. BABYLON.HingeJoint = HingeJoint;
  37245. /**
  37246. * This class represents a dual hinge physics joint (same as wheel joint)
  37247. */
  37248. var Hinge2Joint = (function (_super) {
  37249. __extends(Hinge2Joint, _super);
  37250. function Hinge2Joint(jointData) {
  37251. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  37252. }
  37253. /**
  37254. * Set the motor values.
  37255. * Attention, this function is plugin specific. Engines won't react 100% the same.
  37256. * @param {number} force the force to apply
  37257. * @param {number} maxForce max force for this motor.
  37258. * @param {motorIndex} the motor's index, 0 or 1.
  37259. */
  37260. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  37261. if (motorIndex === void 0) { motorIndex = 0; }
  37262. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  37263. };
  37264. /**
  37265. * Set the motor limits.
  37266. * Attention, this function is plugin specific. Engines won't react 100% the same.
  37267. * @param {number} upperLimit the upper limit
  37268. * @param {number} lowerLimit lower limit
  37269. * @param {motorIndex} the motor's index, 0 or 1.
  37270. */
  37271. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  37272. if (motorIndex === void 0) { motorIndex = 0; }
  37273. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  37274. };
  37275. return Hinge2Joint;
  37276. }(MotorEnabledJoint));
  37277. BABYLON.Hinge2Joint = Hinge2Joint;
  37278. })(BABYLON || (BABYLON = {}));
  37279. //# sourceMappingURL=babylon.physicsJoint.js.map
  37280. var BABYLON;
  37281. (function (BABYLON) {
  37282. var PhysicsImpostor = (function () {
  37283. function PhysicsImpostor(object, type, _options, _scene) {
  37284. if (_options === void 0) { _options = { mass: 0 }; }
  37285. var _this = this;
  37286. this.object = object;
  37287. this.type = type;
  37288. this._options = _options;
  37289. this._scene = _scene;
  37290. this._bodyUpdateRequired = false;
  37291. this._onBeforePhysicsStepCallbacks = new Array();
  37292. this._onAfterPhysicsStepCallbacks = new Array();
  37293. this._onPhysicsCollideCallbacks = [];
  37294. this._deltaPosition = BABYLON.Vector3.Zero();
  37295. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  37296. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  37297. /**
  37298. * this function is executed by the physics engine.
  37299. */
  37300. this.beforeStep = function () {
  37301. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  37302. //conjugate deltaRotation
  37303. if (_this._deltaRotationConjugated) {
  37304. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  37305. }
  37306. else {
  37307. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  37308. }
  37309. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  37310. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  37311. func(_this);
  37312. });
  37313. };
  37314. /**
  37315. * this function is executed by the physics engine.
  37316. */
  37317. this.afterStep = function () {
  37318. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  37319. func(_this);
  37320. });
  37321. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  37322. _this.object.position.addInPlace(_this._deltaPosition);
  37323. if (_this._deltaRotation) {
  37324. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  37325. }
  37326. };
  37327. /**
  37328. * Legacy collision detection event support
  37329. */
  37330. this.onCollideEvent = null;
  37331. //event and body object due to cannon's event-based architecture.
  37332. this.onCollide = function (e) {
  37333. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  37334. return;
  37335. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  37336. if (otherImpostor) {
  37337. // Legacy collision detection event support
  37338. if (_this.onCollideEvent) {
  37339. _this.onCollideEvent(_this, otherImpostor);
  37340. }
  37341. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  37342. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  37343. }).forEach(function (obj) {
  37344. obj.callback(_this, otherImpostor);
  37345. });
  37346. }
  37347. };
  37348. //sanity check!
  37349. if (!this.object) {
  37350. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  37351. return;
  37352. }
  37353. //legacy support for old syntax.
  37354. if (!this._scene && object.getScene) {
  37355. this._scene = object.getScene();
  37356. }
  37357. this._physicsEngine = this._scene.getPhysicsEngine();
  37358. if (!this._physicsEngine) {
  37359. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  37360. }
  37361. else {
  37362. //set the object's quaternion, if not set
  37363. if (!this.object.rotationQuaternion) {
  37364. if (this.object.rotation) {
  37365. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  37366. }
  37367. else {
  37368. this.object.rotationQuaternion = new BABYLON.Quaternion();
  37369. }
  37370. }
  37371. //default options params
  37372. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  37373. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  37374. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  37375. this._joints = [];
  37376. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  37377. if (!this.object.parent) {
  37378. this._init();
  37379. }
  37380. }
  37381. }
  37382. /**
  37383. * This function will completly initialize this impostor.
  37384. * It will create a new body - but only if this mesh has no parent.
  37385. * If it has, this impostor will not be used other than to define the impostor
  37386. * of the child mesh.
  37387. */
  37388. PhysicsImpostor.prototype._init = function () {
  37389. this._physicsEngine.removeImpostor(this);
  37390. this.physicsBody = null;
  37391. this._parent = this._parent || this._getPhysicsParent();
  37392. if (!this.parent) {
  37393. this._physicsEngine.addImpostor(this);
  37394. }
  37395. };
  37396. PhysicsImpostor.prototype._getPhysicsParent = function () {
  37397. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  37398. var parentMesh = this.object.parent;
  37399. return parentMesh.physicsImpostor;
  37400. }
  37401. return;
  37402. };
  37403. /**
  37404. * Should a new body be generated.
  37405. */
  37406. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  37407. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  37408. };
  37409. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  37410. this.forceUpdate();
  37411. };
  37412. /**
  37413. * Force a regeneration of this or the parent's impostor's body.
  37414. * Use under cautious - This will remove all joints already implemented.
  37415. */
  37416. PhysicsImpostor.prototype.forceUpdate = function () {
  37417. this._init();
  37418. if (this.parent) {
  37419. this.parent.forceUpdate();
  37420. }
  37421. };
  37422. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  37423. /*public get mesh(): AbstractMesh {
  37424. return this._mesh;
  37425. }*/
  37426. /**
  37427. * Gets the body that holds this impostor. Either its own, or its parent.
  37428. */
  37429. get: function () {
  37430. return this._parent ? this._parent.physicsBody : this._physicsBody;
  37431. },
  37432. /**
  37433. * Set the physics body. Used mainly by the physics engine/plugin
  37434. */
  37435. set: function (physicsBody) {
  37436. if (this._physicsBody) {
  37437. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  37438. }
  37439. this._physicsBody = physicsBody;
  37440. this.resetUpdateFlags();
  37441. },
  37442. enumerable: true,
  37443. configurable: true
  37444. });
  37445. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  37446. get: function () {
  37447. return this._parent;
  37448. },
  37449. set: function (value) {
  37450. this._parent = value;
  37451. },
  37452. enumerable: true,
  37453. configurable: true
  37454. });
  37455. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  37456. this._bodyUpdateRequired = false;
  37457. };
  37458. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  37459. if (this.object.getBoundingInfo) {
  37460. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  37461. return this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2).multiply(this.object.scaling);
  37462. }
  37463. else {
  37464. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  37465. }
  37466. };
  37467. PhysicsImpostor.prototype.getObjectCenter = function () {
  37468. if (this.object.getBoundingInfo) {
  37469. return this.object.getBoundingInfo().boundingBox.centerWorld;
  37470. }
  37471. else {
  37472. return this.object.position;
  37473. }
  37474. };
  37475. /**
  37476. * Get a specific parametes from the options parameter.
  37477. */
  37478. PhysicsImpostor.prototype.getParam = function (paramName) {
  37479. return this._options[paramName];
  37480. };
  37481. /**
  37482. * Sets a specific parameter in the options given to the physics plugin
  37483. */
  37484. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  37485. this._options[paramName] = value;
  37486. this._bodyUpdateRequired = true;
  37487. };
  37488. /**
  37489. * Specifically change the body's mass option. Won't recreate the physics body object
  37490. */
  37491. PhysicsImpostor.prototype.setMass = function (mass) {
  37492. if (this.getParam("mass") !== mass) {
  37493. this.setParam("mass", mass);
  37494. }
  37495. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  37496. };
  37497. PhysicsImpostor.prototype.getLinearVelocity = function () {
  37498. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  37499. };
  37500. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  37501. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  37502. };
  37503. PhysicsImpostor.prototype.getAngularVelocity = function () {
  37504. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  37505. };
  37506. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  37507. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  37508. };
  37509. /**
  37510. * Execute a function with the physics plugin native code.
  37511. * Provide a function the will have two variables - the world object and the physics body object.
  37512. */
  37513. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  37514. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  37515. };
  37516. /**
  37517. * Register a function that will be executed before the physics world is stepping forward.
  37518. */
  37519. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  37520. this._onBeforePhysicsStepCallbacks.push(func);
  37521. };
  37522. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  37523. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  37524. if (index > -1) {
  37525. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  37526. }
  37527. else {
  37528. BABYLON.Tools.Warn("Function to remove was not found");
  37529. }
  37530. };
  37531. /**
  37532. * Register a function that will be executed after the physics step
  37533. */
  37534. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  37535. this._onAfterPhysicsStepCallbacks.push(func);
  37536. };
  37537. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  37538. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  37539. if (index > -1) {
  37540. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  37541. }
  37542. else {
  37543. BABYLON.Tools.Warn("Function to remove was not found");
  37544. }
  37545. };
  37546. /**
  37547. * register a function that will be executed when this impostor collides against a different body.
  37548. */
  37549. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  37550. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  37551. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  37552. };
  37553. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  37554. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  37555. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  37556. if (index > -1) {
  37557. this._onPhysicsCollideCallbacks.splice(index, 1);
  37558. }
  37559. else {
  37560. BABYLON.Tools.Warn("Function to remove was not found");
  37561. }
  37562. };
  37563. /**
  37564. * Apply a force
  37565. */
  37566. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  37567. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  37568. };
  37569. /**
  37570. * Apply an impulse
  37571. */
  37572. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  37573. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  37574. };
  37575. /**
  37576. * A help function to create a joint.
  37577. */
  37578. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  37579. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  37580. this.addJoint(otherImpostor, joint);
  37581. };
  37582. /**
  37583. * Add a joint to this impostor with a different impostor.
  37584. */
  37585. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  37586. this._joints.push({
  37587. otherImpostor: otherImpostor,
  37588. joint: joint
  37589. });
  37590. this._physicsEngine.addJoint(this, otherImpostor, joint);
  37591. };
  37592. /**
  37593. * Will keep this body still, in a sleep mode.
  37594. */
  37595. PhysicsImpostor.prototype.sleep = function () {
  37596. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  37597. };
  37598. /**
  37599. * Wake the body up.
  37600. */
  37601. PhysicsImpostor.prototype.wakeUp = function () {
  37602. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  37603. };
  37604. PhysicsImpostor.prototype.clone = function (newObject) {
  37605. if (!newObject)
  37606. return null;
  37607. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  37608. };
  37609. PhysicsImpostor.prototype.dispose = function () {
  37610. var _this = this;
  37611. //no dispose if no physics engine is available.
  37612. if (!this._physicsEngine) {
  37613. return;
  37614. }
  37615. this._joints.forEach(function (j) {
  37616. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  37617. });
  37618. //dispose the physics body
  37619. this._physicsEngine.removeImpostor(this);
  37620. if (this.parent) {
  37621. this.parent.forceUpdate();
  37622. }
  37623. else {
  37624. /*this._object.getChildMeshes().forEach(function(mesh) {
  37625. if (mesh.physicsImpostor) {
  37626. if (disposeChildren) {
  37627. mesh.physicsImpostor.dispose();
  37628. mesh.physicsImpostor = null;
  37629. }
  37630. }
  37631. })*/
  37632. }
  37633. };
  37634. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  37635. this._deltaPosition.copyFrom(position);
  37636. };
  37637. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  37638. if (!this._deltaRotation) {
  37639. this._deltaRotation = new BABYLON.Quaternion();
  37640. }
  37641. this._deltaRotation.copyFrom(rotation);
  37642. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  37643. };
  37644. return PhysicsImpostor;
  37645. }());
  37646. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  37647. //Impostor types
  37648. PhysicsImpostor.NoImpostor = 0;
  37649. PhysicsImpostor.SphereImpostor = 1;
  37650. PhysicsImpostor.BoxImpostor = 2;
  37651. PhysicsImpostor.PlaneImpostor = 3;
  37652. PhysicsImpostor.MeshImpostor = 4;
  37653. PhysicsImpostor.CylinderImpostor = 7;
  37654. PhysicsImpostor.ParticleImpostor = 8;
  37655. PhysicsImpostor.HeightmapImpostor = 9;
  37656. BABYLON.PhysicsImpostor = PhysicsImpostor;
  37657. })(BABYLON || (BABYLON = {}));
  37658. //# sourceMappingURL=babylon.physicsImpostor.js.map
  37659. var BABYLON;
  37660. (function (BABYLON) {
  37661. var PhysicsEngine = (function () {
  37662. function PhysicsEngine(gravity, _physicsPlugin) {
  37663. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  37664. this._physicsPlugin = _physicsPlugin;
  37665. //new methods and parameters
  37666. this._impostors = [];
  37667. this._joints = [];
  37668. if (!this._physicsPlugin.isSupported()) {
  37669. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  37670. + "Please make sure it is included.");
  37671. }
  37672. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  37673. this.setGravity(gravity);
  37674. this.setTimeStep();
  37675. }
  37676. PhysicsEngine.prototype.setGravity = function (gravity) {
  37677. this.gravity = gravity;
  37678. this._physicsPlugin.setGravity(this.gravity);
  37679. };
  37680. /**
  37681. * Set the time step of the physics engine.
  37682. * default is 1/60.
  37683. * To slow it down, enter 1/600 for example.
  37684. * To speed it up, 1/30
  37685. * @param {number} newTimeStep the new timestep to apply to this world.
  37686. */
  37687. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  37688. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  37689. this._physicsPlugin.setTimeStep(newTimeStep);
  37690. };
  37691. PhysicsEngine.prototype.dispose = function () {
  37692. this._impostors.forEach(function (impostor) {
  37693. impostor.dispose();
  37694. });
  37695. this._physicsPlugin.dispose();
  37696. };
  37697. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  37698. return this._physicsPlugin.name;
  37699. };
  37700. /**
  37701. * Adding a new impostor for the impostor tracking.
  37702. * This will be done by the impostor itself.
  37703. * @param {PhysicsImpostor} impostor the impostor to add
  37704. */
  37705. PhysicsEngine.prototype.addImpostor = function (impostor) {
  37706. impostor.uniqueId = this._impostors.push(impostor);
  37707. //if no parent, generate the body
  37708. if (!impostor.parent) {
  37709. this._physicsPlugin.generatePhysicsBody(impostor);
  37710. }
  37711. };
  37712. /**
  37713. * Remove an impostor from the engine.
  37714. * This impostor and its mesh will not longer be updated by the physics engine.
  37715. * @param {PhysicsImpostor} impostor the impostor to remove
  37716. */
  37717. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  37718. var index = this._impostors.indexOf(impostor);
  37719. if (index > -1) {
  37720. var removed = this._impostors.splice(index, 1);
  37721. //Is it needed?
  37722. if (removed.length) {
  37723. //this will also remove it from the world.
  37724. removed[0].physicsBody = null;
  37725. }
  37726. }
  37727. };
  37728. /**
  37729. * Add a joint to the physics engine
  37730. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  37731. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  37732. * @param {PhysicsJoint} the joint that will connect both impostors.
  37733. */
  37734. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  37735. var impostorJoint = {
  37736. mainImpostor: mainImpostor,
  37737. connectedImpostor: connectedImpostor,
  37738. joint: joint
  37739. };
  37740. joint.physicsPlugin = this._physicsPlugin;
  37741. this._joints.push(impostorJoint);
  37742. this._physicsPlugin.generateJoint(impostorJoint);
  37743. };
  37744. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  37745. var matchingJoints = this._joints.filter(function (impostorJoint) {
  37746. return (impostorJoint.connectedImpostor === connectedImpostor
  37747. && impostorJoint.joint === joint
  37748. && impostorJoint.mainImpostor === mainImpostor);
  37749. });
  37750. if (matchingJoints.length) {
  37751. this._physicsPlugin.removeJoint(matchingJoints[0]);
  37752. //TODO remove it from the list as well
  37753. }
  37754. };
  37755. /**
  37756. * Called by the scene. no need to call it.
  37757. */
  37758. PhysicsEngine.prototype._step = function (delta) {
  37759. var _this = this;
  37760. //check if any mesh has no body / requires an update
  37761. this._impostors.forEach(function (impostor) {
  37762. if (impostor.isBodyInitRequired()) {
  37763. _this._physicsPlugin.generatePhysicsBody(impostor);
  37764. }
  37765. });
  37766. if (delta > 0.1) {
  37767. delta = 0.1;
  37768. }
  37769. else if (delta <= 0) {
  37770. delta = 1.0 / 60.0;
  37771. }
  37772. this._physicsPlugin.executeStep(delta, this._impostors);
  37773. };
  37774. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  37775. return this._physicsPlugin;
  37776. };
  37777. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  37778. for (var i = 0; i < this._impostors.length; ++i) {
  37779. if (this._impostors[i].object === object) {
  37780. return this._impostors[i];
  37781. }
  37782. }
  37783. };
  37784. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  37785. for (var i = 0; i < this._impostors.length; ++i) {
  37786. if (this._impostors[i].physicsBody === body) {
  37787. return this._impostors[i];
  37788. }
  37789. }
  37790. };
  37791. return PhysicsEngine;
  37792. }());
  37793. // Statics
  37794. PhysicsEngine.Epsilon = 0.001;
  37795. BABYLON.PhysicsEngine = PhysicsEngine;
  37796. })(BABYLON || (BABYLON = {}));
  37797. //# sourceMappingURL=babylon.physicsEngine.js.map
  37798. var BABYLON;
  37799. (function (BABYLON) {
  37800. var VertexData = (function () {
  37801. function VertexData() {
  37802. }
  37803. VertexData.prototype.set = function (data, kind) {
  37804. switch (kind) {
  37805. case BABYLON.VertexBuffer.PositionKind:
  37806. this.positions = data;
  37807. break;
  37808. case BABYLON.VertexBuffer.NormalKind:
  37809. this.normals = data;
  37810. break;
  37811. case BABYLON.VertexBuffer.TangentKind:
  37812. this.tangents = data;
  37813. break;
  37814. case BABYLON.VertexBuffer.UVKind:
  37815. this.uvs = data;
  37816. break;
  37817. case BABYLON.VertexBuffer.UV2Kind:
  37818. this.uvs2 = data;
  37819. break;
  37820. case BABYLON.VertexBuffer.UV3Kind:
  37821. this.uvs3 = data;
  37822. break;
  37823. case BABYLON.VertexBuffer.UV4Kind:
  37824. this.uvs4 = data;
  37825. break;
  37826. case BABYLON.VertexBuffer.UV5Kind:
  37827. this.uvs5 = data;
  37828. break;
  37829. case BABYLON.VertexBuffer.UV6Kind:
  37830. this.uvs6 = data;
  37831. break;
  37832. case BABYLON.VertexBuffer.ColorKind:
  37833. this.colors = data;
  37834. break;
  37835. case BABYLON.VertexBuffer.MatricesIndicesKind:
  37836. this.matricesIndices = data;
  37837. break;
  37838. case BABYLON.VertexBuffer.MatricesWeightsKind:
  37839. this.matricesWeights = data;
  37840. break;
  37841. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  37842. this.matricesIndicesExtra = data;
  37843. break;
  37844. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  37845. this.matricesWeightsExtra = data;
  37846. break;
  37847. }
  37848. };
  37849. /**
  37850. * Associates the vertexData to the passed Mesh.
  37851. * Sets it as updatable or not (default `false`).
  37852. * Returns the VertexData.
  37853. */
  37854. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  37855. this._applyTo(mesh, updatable);
  37856. return this;
  37857. };
  37858. /**
  37859. * Associates the vertexData to the passed Geometry.
  37860. * Sets it as updatable or not (default `false`).
  37861. * Returns the VertexData.
  37862. */
  37863. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  37864. this._applyTo(geometry, updatable);
  37865. return this;
  37866. };
  37867. /**
  37868. * Updates the associated mesh.
  37869. * Returns the VertexData.
  37870. */
  37871. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  37872. this._update(mesh);
  37873. return this;
  37874. };
  37875. /**
  37876. * Updates the associated geometry.
  37877. * Returns the VertexData.
  37878. */
  37879. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  37880. this._update(geometry);
  37881. return this;
  37882. };
  37883. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  37884. if (this.positions) {
  37885. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  37886. }
  37887. if (this.normals) {
  37888. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  37889. }
  37890. if (this.tangents) {
  37891. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  37892. }
  37893. if (this.uvs) {
  37894. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  37895. }
  37896. if (this.uvs2) {
  37897. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  37898. }
  37899. if (this.uvs3) {
  37900. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  37901. }
  37902. if (this.uvs4) {
  37903. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  37904. }
  37905. if (this.uvs5) {
  37906. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  37907. }
  37908. if (this.uvs6) {
  37909. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  37910. }
  37911. if (this.colors) {
  37912. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  37913. }
  37914. if (this.matricesIndices) {
  37915. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  37916. }
  37917. if (this.matricesWeights) {
  37918. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  37919. }
  37920. if (this.matricesIndicesExtra) {
  37921. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  37922. }
  37923. if (this.matricesWeightsExtra) {
  37924. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  37925. }
  37926. if (this.indices) {
  37927. meshOrGeometry.setIndices(this.indices);
  37928. }
  37929. return this;
  37930. };
  37931. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  37932. if (this.positions) {
  37933. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  37934. }
  37935. if (this.normals) {
  37936. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  37937. }
  37938. if (this.tangents) {
  37939. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  37940. }
  37941. if (this.uvs) {
  37942. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  37943. }
  37944. if (this.uvs2) {
  37945. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  37946. }
  37947. if (this.uvs3) {
  37948. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  37949. }
  37950. if (this.uvs4) {
  37951. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  37952. }
  37953. if (this.uvs5) {
  37954. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  37955. }
  37956. if (this.uvs6) {
  37957. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  37958. }
  37959. if (this.colors) {
  37960. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  37961. }
  37962. if (this.matricesIndices) {
  37963. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  37964. }
  37965. if (this.matricesWeights) {
  37966. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  37967. }
  37968. if (this.matricesIndicesExtra) {
  37969. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  37970. }
  37971. if (this.matricesWeightsExtra) {
  37972. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  37973. }
  37974. if (this.indices) {
  37975. meshOrGeometry.setIndices(this.indices);
  37976. }
  37977. return this;
  37978. };
  37979. /**
  37980. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  37981. * Returns the VertexData.
  37982. */
  37983. VertexData.prototype.transform = function (matrix) {
  37984. var transformed = BABYLON.Vector3.Zero();
  37985. var index;
  37986. if (this.positions) {
  37987. var position = BABYLON.Vector3.Zero();
  37988. for (index = 0; index < this.positions.length; index += 3) {
  37989. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  37990. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  37991. this.positions[index] = transformed.x;
  37992. this.positions[index + 1] = transformed.y;
  37993. this.positions[index + 2] = transformed.z;
  37994. }
  37995. }
  37996. if (this.normals) {
  37997. var normal = BABYLON.Vector3.Zero();
  37998. for (index = 0; index < this.normals.length; index += 3) {
  37999. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  38000. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  38001. this.normals[index] = transformed.x;
  38002. this.normals[index + 1] = transformed.y;
  38003. this.normals[index + 2] = transformed.z;
  38004. }
  38005. }
  38006. if (this.tangents) {
  38007. var tangent = BABYLON.Vector4.Zero();
  38008. var tangentTransformed = BABYLON.Vector4.Zero();
  38009. for (index = 0; index < this.tangents.length; index += 4) {
  38010. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  38011. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  38012. this.tangents[index] = tangentTransformed.x;
  38013. this.tangents[index + 1] = tangentTransformed.y;
  38014. this.tangents[index + 2] = tangentTransformed.z;
  38015. this.tangents[index + 3] = tangentTransformed.w;
  38016. }
  38017. }
  38018. return this;
  38019. };
  38020. /**
  38021. * Merges the passed VertexData into the current one.
  38022. * Returns the modified VertexData.
  38023. */
  38024. VertexData.prototype.merge = function (other) {
  38025. if (other.indices) {
  38026. if (!this.indices) {
  38027. this.indices = [];
  38028. }
  38029. var offset = this.positions ? this.positions.length / 3 : 0;
  38030. for (var index = 0; index < other.indices.length; index++) {
  38031. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  38032. this.indices.push(other.indices[index] + offset);
  38033. }
  38034. }
  38035. this.positions = this._mergeElement(this.positions, other.positions);
  38036. this.normals = this._mergeElement(this.normals, other.normals);
  38037. this.tangents = this._mergeElement(this.tangents, other.tangents);
  38038. this.uvs = this._mergeElement(this.uvs, other.uvs);
  38039. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  38040. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  38041. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  38042. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  38043. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  38044. this.colors = this._mergeElement(this.colors, other.colors);
  38045. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  38046. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  38047. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  38048. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  38049. return this;
  38050. };
  38051. VertexData.prototype._mergeElement = function (source, other) {
  38052. if (!other)
  38053. return source;
  38054. if (!source)
  38055. return other;
  38056. var len = other.length + source.length;
  38057. var isSrcTypedArray = source instanceof Float32Array;
  38058. var isOthTypedArray = other instanceof Float32Array;
  38059. // use non-loop method when the source is Float32Array
  38060. if (isSrcTypedArray) {
  38061. var ret32 = new Float32Array(len);
  38062. ret32.set(source);
  38063. ret32.set(other, source.length);
  38064. return ret32;
  38065. // source is number[], when other is also use concat
  38066. }
  38067. else if (!isOthTypedArray) {
  38068. return source.concat(other);
  38069. // source is a number[], but other is a Float32Array, loop required
  38070. }
  38071. else {
  38072. var ret = source.slice(0); // copy source to a separate array
  38073. for (var i = 0, len = other.length; i < len; i++) {
  38074. ret.push(other[i]);
  38075. }
  38076. return ret;
  38077. }
  38078. };
  38079. /**
  38080. * Serializes the VertexData.
  38081. * Returns a serialized object.
  38082. */
  38083. VertexData.prototype.serialize = function () {
  38084. var serializationObject = this.serialize();
  38085. if (this.positions) {
  38086. serializationObject.positions = this.positions;
  38087. }
  38088. if (this.normals) {
  38089. serializationObject.normals = this.normals;
  38090. }
  38091. if (this.tangents) {
  38092. serializationObject.tangents = this.tangents;
  38093. }
  38094. if (this.uvs) {
  38095. serializationObject.uvs = this.uvs;
  38096. }
  38097. if (this.uvs2) {
  38098. serializationObject.uvs2 = this.uvs2;
  38099. }
  38100. if (this.uvs3) {
  38101. serializationObject.uvs3 = this.uvs3;
  38102. }
  38103. if (this.uvs4) {
  38104. serializationObject.uvs4 = this.uvs4;
  38105. }
  38106. if (this.uvs5) {
  38107. serializationObject.uvs5 = this.uvs5;
  38108. }
  38109. if (this.uvs6) {
  38110. serializationObject.uvs6 = this.uvs6;
  38111. }
  38112. if (this.colors) {
  38113. serializationObject.colors = this.colors;
  38114. }
  38115. if (this.matricesIndices) {
  38116. serializationObject.matricesIndices = this.matricesIndices;
  38117. serializationObject.matricesIndices._isExpanded = true;
  38118. }
  38119. if (this.matricesWeights) {
  38120. serializationObject.matricesWeights = this.matricesWeights;
  38121. }
  38122. if (this.matricesIndicesExtra) {
  38123. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  38124. serializationObject.matricesIndicesExtra._isExpanded = true;
  38125. }
  38126. if (this.matricesWeightsExtra) {
  38127. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  38128. }
  38129. serializationObject.indices = this.indices;
  38130. return serializationObject;
  38131. };
  38132. // Statics
  38133. /**
  38134. * Returns the object VertexData associated to the passed mesh.
  38135. */
  38136. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  38137. return VertexData._ExtractFrom(mesh, copyWhenShared);
  38138. };
  38139. /**
  38140. * Returns the object VertexData associated to the passed geometry.
  38141. */
  38142. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  38143. return VertexData._ExtractFrom(geometry, copyWhenShared);
  38144. };
  38145. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  38146. var result = new VertexData();
  38147. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38148. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  38149. }
  38150. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38151. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  38152. }
  38153. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38154. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared);
  38155. }
  38156. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38157. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  38158. }
  38159. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38160. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  38161. }
  38162. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38163. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  38164. }
  38165. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38166. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  38167. }
  38168. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38169. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  38170. }
  38171. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38172. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  38173. }
  38174. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38175. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  38176. }
  38177. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38178. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  38179. }
  38180. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38181. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  38182. }
  38183. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  38184. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  38185. }
  38186. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  38187. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  38188. }
  38189. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  38190. return result;
  38191. };
  38192. /**
  38193. * Creates the vertexData of the Ribbon.
  38194. */
  38195. VertexData.CreateRibbon = function (options) {
  38196. var pathArray = options.pathArray;
  38197. var closeArray = options.closeArray || false;
  38198. var closePath = options.closePath || false;
  38199. var invertUV = options.invertUV || false;
  38200. var defaultOffset = Math.floor(pathArray[0].length / 2);
  38201. var offset = options.offset || defaultOffset;
  38202. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  38203. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38204. var customUV = options.uvs;
  38205. var customColors = options.colors;
  38206. var positions = [];
  38207. var indices = [];
  38208. var normals = [];
  38209. var uvs = [];
  38210. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  38211. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  38212. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  38213. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  38214. var minlg; // minimal length among all paths from pathArray
  38215. var lg = []; // array of path lengths : nb of vertex per path
  38216. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  38217. var p; // path iterator
  38218. var i; // point iterator
  38219. var j; // point iterator
  38220. // if single path in pathArray
  38221. if (pathArray.length < 2) {
  38222. var ar1 = [];
  38223. var ar2 = [];
  38224. for (i = 0; i < pathArray[0].length - offset; i++) {
  38225. ar1.push(pathArray[0][i]);
  38226. ar2.push(pathArray[0][i + offset]);
  38227. }
  38228. pathArray = [ar1, ar2];
  38229. }
  38230. // positions and horizontal distances (u)
  38231. var idc = 0;
  38232. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  38233. var path;
  38234. var l;
  38235. minlg = pathArray[0].length;
  38236. var vectlg;
  38237. var dist;
  38238. for (p = 0; p < pathArray.length; p++) {
  38239. uTotalDistance[p] = 0;
  38240. us[p] = [0];
  38241. path = pathArray[p];
  38242. l = path.length;
  38243. minlg = (minlg < l) ? minlg : l;
  38244. j = 0;
  38245. while (j < l) {
  38246. positions.push(path[j].x, path[j].y, path[j].z);
  38247. if (j > 0) {
  38248. vectlg = path[j].subtract(path[j - 1]).length();
  38249. dist = vectlg + uTotalDistance[p];
  38250. us[p].push(dist);
  38251. uTotalDistance[p] = dist;
  38252. }
  38253. j++;
  38254. }
  38255. if (closePath) {
  38256. j--;
  38257. positions.push(path[0].x, path[0].y, path[0].z);
  38258. vectlg = path[j].subtract(path[0]).length();
  38259. dist = vectlg + uTotalDistance[p];
  38260. us[p].push(dist);
  38261. uTotalDistance[p] = dist;
  38262. }
  38263. lg[p] = l + closePathCorr;
  38264. idx[p] = idc;
  38265. idc += (l + closePathCorr);
  38266. }
  38267. // vertical distances (v)
  38268. var path1;
  38269. var path2;
  38270. var vertex1;
  38271. var vertex2;
  38272. for (i = 0; i < minlg + closePathCorr; i++) {
  38273. vTotalDistance[i] = 0;
  38274. vs[i] = [0];
  38275. for (p = 0; p < pathArray.length - 1; p++) {
  38276. path1 = pathArray[p];
  38277. path2 = pathArray[p + 1];
  38278. if (i === minlg) {
  38279. vertex1 = path1[0];
  38280. vertex2 = path2[0];
  38281. }
  38282. else {
  38283. vertex1 = path1[i];
  38284. vertex2 = path2[i];
  38285. }
  38286. vectlg = vertex2.subtract(vertex1).length();
  38287. dist = vectlg + vTotalDistance[i];
  38288. vs[i].push(dist);
  38289. vTotalDistance[i] = dist;
  38290. }
  38291. if (closeArray) {
  38292. path1 = pathArray[p];
  38293. path2 = pathArray[0];
  38294. if (i === minlg) {
  38295. vertex2 = path2[0];
  38296. }
  38297. vectlg = vertex2.subtract(vertex1).length();
  38298. dist = vectlg + vTotalDistance[i];
  38299. vTotalDistance[i] = dist;
  38300. }
  38301. }
  38302. // uvs
  38303. var u;
  38304. var v;
  38305. if (customUV) {
  38306. for (p = 0; p < customUV.length; p++) {
  38307. uvs.push(customUV[p].x, customUV[p].y);
  38308. }
  38309. }
  38310. else {
  38311. for (p = 0; p < pathArray.length; p++) {
  38312. for (i = 0; i < minlg + closePathCorr; i++) {
  38313. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  38314. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  38315. if (invertUV) {
  38316. uvs.push(v, u);
  38317. }
  38318. else {
  38319. uvs.push(u, v);
  38320. }
  38321. }
  38322. }
  38323. }
  38324. // indices
  38325. p = 0; // path index
  38326. var pi = 0; // positions array index
  38327. var l1 = lg[p] - 1; // path1 length
  38328. var l2 = lg[p + 1] - 1; // path2 length
  38329. var min = (l1 < l2) ? l1 : l2; // current path stop index
  38330. var shft = idx[1] - idx[0]; // shift
  38331. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  38332. while (pi <= min && p < path1nb) {
  38333. // 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
  38334. indices.push(pi, pi + shft, pi + 1);
  38335. indices.push(pi + shft + 1, pi + 1, pi + shft);
  38336. pi += 1;
  38337. if (pi === min) {
  38338. p++;
  38339. if (p === lg.length - 1) {
  38340. shft = idx[0] - idx[p];
  38341. l1 = lg[p] - 1;
  38342. l2 = lg[0] - 1;
  38343. }
  38344. else {
  38345. shft = idx[p + 1] - idx[p];
  38346. l1 = lg[p] - 1;
  38347. l2 = lg[p + 1] - 1;
  38348. }
  38349. pi = idx[p];
  38350. min = (l1 < l2) ? l1 + pi : l2 + pi;
  38351. }
  38352. }
  38353. // normals
  38354. VertexData.ComputeNormals(positions, indices, normals);
  38355. if (closePath) {
  38356. var indexFirst = 0;
  38357. var indexLast = 0;
  38358. for (p = 0; p < pathArray.length; p++) {
  38359. indexFirst = idx[p] * 3;
  38360. if (p + 1 < pathArray.length) {
  38361. indexLast = (idx[p + 1] - 1) * 3;
  38362. }
  38363. else {
  38364. indexLast = normals.length - 3;
  38365. }
  38366. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  38367. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  38368. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  38369. normals[indexLast] = normals[indexFirst];
  38370. normals[indexLast + 1] = normals[indexFirst + 1];
  38371. normals[indexLast + 2] = normals[indexFirst + 2];
  38372. }
  38373. }
  38374. // sides
  38375. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38376. // Colors
  38377. if (customColors) {
  38378. var colors = new Float32Array(customColors.length * 4);
  38379. for (var c = 0; c < customColors.length; c++) {
  38380. colors[c * 4] = customColors[c].r;
  38381. colors[c * 4 + 1] = customColors[c].g;
  38382. colors[c * 4 + 2] = customColors[c].b;
  38383. colors[c * 4 + 3] = customColors[c].a;
  38384. }
  38385. }
  38386. // Result
  38387. var vertexData = new VertexData();
  38388. var positions32 = new Float32Array(positions);
  38389. var normals32 = new Float32Array(normals);
  38390. var uvs32 = new Float32Array(uvs);
  38391. vertexData.indices = indices;
  38392. vertexData.positions = positions32;
  38393. vertexData.normals = normals32;
  38394. vertexData.uvs = uvs32;
  38395. if (customColors) {
  38396. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  38397. }
  38398. if (closePath) {
  38399. vertexData._idx = idx;
  38400. }
  38401. return vertexData;
  38402. };
  38403. /**
  38404. * Creates the VertexData of the Box.
  38405. */
  38406. VertexData.CreateBox = function (options) {
  38407. var normalsSource = [
  38408. new BABYLON.Vector3(0, 0, 1),
  38409. new BABYLON.Vector3(0, 0, -1),
  38410. new BABYLON.Vector3(1, 0, 0),
  38411. new BABYLON.Vector3(-1, 0, 0),
  38412. new BABYLON.Vector3(0, 1, 0),
  38413. new BABYLON.Vector3(0, -1, 0)
  38414. ];
  38415. var indices = [];
  38416. var positions = [];
  38417. var normals = [];
  38418. var uvs = [];
  38419. var width = options.width || options.size || 1;
  38420. var height = options.height || options.size || 1;
  38421. var depth = options.depth || options.size || 1;
  38422. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38423. var faceUV = options.faceUV || new Array(6);
  38424. var faceColors = options.faceColors;
  38425. var colors = [];
  38426. // default face colors and UV if undefined
  38427. for (var f = 0; f < 6; f++) {
  38428. if (faceUV[f] === undefined) {
  38429. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38430. }
  38431. if (faceColors && faceColors[f] === undefined) {
  38432. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38433. }
  38434. }
  38435. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  38436. // Create each face in turn.
  38437. for (var index = 0; index < normalsSource.length; index++) {
  38438. var normal = normalsSource[index];
  38439. // Get two vectors perpendicular to the face normal and to each other.
  38440. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  38441. var side2 = BABYLON.Vector3.Cross(normal, side1);
  38442. // Six indices (two triangles) per face.
  38443. var verticesLength = positions.length / 3;
  38444. indices.push(verticesLength);
  38445. indices.push(verticesLength + 1);
  38446. indices.push(verticesLength + 2);
  38447. indices.push(verticesLength);
  38448. indices.push(verticesLength + 2);
  38449. indices.push(verticesLength + 3);
  38450. // Four vertices per face.
  38451. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  38452. positions.push(vertex.x, vertex.y, vertex.z);
  38453. normals.push(normal.x, normal.y, normal.z);
  38454. uvs.push(faceUV[index].z, faceUV[index].w);
  38455. if (faceColors) {
  38456. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38457. }
  38458. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  38459. positions.push(vertex.x, vertex.y, vertex.z);
  38460. normals.push(normal.x, normal.y, normal.z);
  38461. uvs.push(faceUV[index].x, faceUV[index].w);
  38462. if (faceColors) {
  38463. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38464. }
  38465. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  38466. positions.push(vertex.x, vertex.y, vertex.z);
  38467. normals.push(normal.x, normal.y, normal.z);
  38468. uvs.push(faceUV[index].x, faceUV[index].y);
  38469. if (faceColors) {
  38470. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38471. }
  38472. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  38473. positions.push(vertex.x, vertex.y, vertex.z);
  38474. normals.push(normal.x, normal.y, normal.z);
  38475. uvs.push(faceUV[index].z, faceUV[index].y);
  38476. if (faceColors) {
  38477. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38478. }
  38479. }
  38480. // sides
  38481. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38482. // Result
  38483. var vertexData = new VertexData();
  38484. vertexData.indices = indices;
  38485. vertexData.positions = positions;
  38486. vertexData.normals = normals;
  38487. vertexData.uvs = uvs;
  38488. if (faceColors) {
  38489. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38490. vertexData.colors = totalColors;
  38491. }
  38492. return vertexData;
  38493. };
  38494. /**
  38495. * Creates the VertexData of the Sphere.
  38496. */
  38497. VertexData.CreateSphere = function (options) {
  38498. var segments = options.segments || 32;
  38499. var diameterX = options.diameterX || options.diameter || 1;
  38500. var diameterY = options.diameterY || options.diameter || 1;
  38501. var diameterZ = options.diameterZ || options.diameter || 1;
  38502. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38503. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  38504. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38505. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  38506. var totalZRotationSteps = 2 + segments;
  38507. var totalYRotationSteps = 2 * totalZRotationSteps;
  38508. var indices = [];
  38509. var positions = [];
  38510. var normals = [];
  38511. var uvs = [];
  38512. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  38513. var normalizedZ = zRotationStep / totalZRotationSteps;
  38514. var angleZ = normalizedZ * Math.PI * slice;
  38515. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  38516. var normalizedY = yRotationStep / totalYRotationSteps;
  38517. var angleY = normalizedY * Math.PI * 2 * arc;
  38518. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  38519. var rotationY = BABYLON.Matrix.RotationY(angleY);
  38520. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  38521. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  38522. var vertex = complete.multiply(radius);
  38523. var normal = complete.divide(radius).normalize();
  38524. positions.push(vertex.x, vertex.y, vertex.z);
  38525. normals.push(normal.x, normal.y, normal.z);
  38526. uvs.push(normalizedY, normalizedZ);
  38527. }
  38528. if (zRotationStep > 0) {
  38529. var verticesCount = positions.length / 3;
  38530. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  38531. indices.push((firstIndex));
  38532. indices.push((firstIndex + 1));
  38533. indices.push(firstIndex + totalYRotationSteps + 1);
  38534. indices.push((firstIndex + totalYRotationSteps + 1));
  38535. indices.push((firstIndex + 1));
  38536. indices.push((firstIndex + totalYRotationSteps + 2));
  38537. }
  38538. }
  38539. }
  38540. // Sides
  38541. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38542. // Result
  38543. var vertexData = new VertexData();
  38544. vertexData.indices = indices;
  38545. vertexData.positions = positions;
  38546. vertexData.normals = normals;
  38547. vertexData.uvs = uvs;
  38548. return vertexData;
  38549. };
  38550. /**
  38551. * Creates the VertexData of the Cylinder or Cone.
  38552. */
  38553. VertexData.CreateCylinder = function (options) {
  38554. var height = options.height || 2;
  38555. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  38556. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  38557. var tessellation = options.tessellation || 24;
  38558. var subdivisions = options.subdivisions || 1;
  38559. var hasRings = options.hasRings;
  38560. var enclose = options.enclose;
  38561. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38562. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38563. var faceUV = options.faceUV || new Array(3);
  38564. var faceColors = options.faceColors;
  38565. // default face colors and UV if undefined
  38566. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  38567. var ringNb = (hasRings) ? subdivisions : 1;
  38568. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  38569. var f;
  38570. for (f = 0; f < surfaceNb; f++) {
  38571. if (faceColors && faceColors[f] === undefined) {
  38572. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38573. }
  38574. }
  38575. for (f = 0; f < surfaceNb; f++) {
  38576. if (faceUV && faceUV[f] === undefined) {
  38577. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38578. }
  38579. }
  38580. var indices = [];
  38581. var positions = [];
  38582. var normals = [];
  38583. var uvs = [];
  38584. var colors = [];
  38585. var angle_step = Math.PI * 2 * arc / tessellation;
  38586. var angle;
  38587. var h;
  38588. var radius;
  38589. var tan = (diameterBottom - diameterTop) / 2 / height;
  38590. var ringVertex = BABYLON.Vector3.Zero();
  38591. var ringNormal = BABYLON.Vector3.Zero();
  38592. var ringFirstVertex = BABYLON.Vector3.Zero();
  38593. var ringFirstNormal = BABYLON.Vector3.Zero();
  38594. var quadNormal = BABYLON.Vector3.Zero();
  38595. var Y = BABYLON.Axis.Y;
  38596. // positions, normals, uvs
  38597. var i;
  38598. var j;
  38599. var r;
  38600. var ringIdx = 1;
  38601. var s = 1; // surface index
  38602. var cs = 0;
  38603. var v = 0;
  38604. for (i = 0; i <= subdivisions; i++) {
  38605. h = i / subdivisions;
  38606. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  38607. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  38608. for (r = 0; r < ringIdx; r++) {
  38609. if (hasRings) {
  38610. s += r;
  38611. }
  38612. if (enclose) {
  38613. s += 2 * r;
  38614. }
  38615. for (j = 0; j <= tessellation; j++) {
  38616. angle = j * angle_step;
  38617. // position
  38618. ringVertex.x = Math.cos(-angle) * radius;
  38619. ringVertex.y = -height / 2 + h * height;
  38620. ringVertex.z = Math.sin(-angle) * radius;
  38621. // normal
  38622. if (diameterTop === 0 && i === subdivisions) {
  38623. // if no top cap, reuse former normals
  38624. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  38625. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  38626. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  38627. }
  38628. else {
  38629. ringNormal.x = ringVertex.x;
  38630. ringNormal.z = ringVertex.z;
  38631. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  38632. ringNormal.normalize();
  38633. }
  38634. // keep first ring vertex values for enclose
  38635. if (j === 0) {
  38636. ringFirstVertex.copyFrom(ringVertex);
  38637. ringFirstNormal.copyFrom(ringNormal);
  38638. }
  38639. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38640. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  38641. if (hasRings) {
  38642. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  38643. }
  38644. else {
  38645. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  38646. }
  38647. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  38648. if (faceColors) {
  38649. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  38650. }
  38651. }
  38652. // if enclose, add four vertices and their dedicated normals
  38653. if (arc !== 1 && enclose) {
  38654. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38655. positions.push(0, ringVertex.y, 0);
  38656. positions.push(0, ringVertex.y, 0);
  38657. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  38658. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  38659. quadNormal.normalize();
  38660. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38661. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  38662. quadNormal.normalize();
  38663. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38664. if (hasRings) {
  38665. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  38666. }
  38667. else {
  38668. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  38669. }
  38670. uvs.push(faceUV[s + 1].x, v);
  38671. uvs.push(faceUV[s + 1].z, v);
  38672. if (hasRings) {
  38673. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  38674. }
  38675. else {
  38676. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  38677. }
  38678. uvs.push(faceUV[s + 2].x, v);
  38679. uvs.push(faceUV[s + 2].z, v);
  38680. if (faceColors) {
  38681. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38682. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38683. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38684. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38685. }
  38686. }
  38687. if (cs !== s) {
  38688. cs = s;
  38689. }
  38690. }
  38691. }
  38692. // indices
  38693. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  38694. var s;
  38695. i = 0;
  38696. for (s = 0; s < subdivisions; s++) {
  38697. for (j = 0; j < tessellation; j++) {
  38698. var i0 = i * (e + 1) + j;
  38699. var i1 = (i + 1) * (e + 1) + j;
  38700. var i2 = i * (e + 1) + (j + 1);
  38701. var i3 = (i + 1) * (e + 1) + (j + 1);
  38702. indices.push(i0, i1, i2);
  38703. indices.push(i3, i2, i1);
  38704. }
  38705. if (arc !== 1 && enclose) {
  38706. indices.push(i0 + 2, i1 + 2, i2 + 2);
  38707. indices.push(i3 + 2, i2 + 2, i1 + 2);
  38708. indices.push(i0 + 4, i1 + 4, i2 + 4);
  38709. indices.push(i3 + 4, i2 + 4, i1 + 4);
  38710. }
  38711. i = (hasRings) ? (i + 2) : (i + 1);
  38712. }
  38713. // Caps
  38714. var createCylinderCap = function (isTop) {
  38715. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  38716. if (radius === 0) {
  38717. return;
  38718. }
  38719. // Cap positions, normals & uvs
  38720. var angle;
  38721. var circleVector;
  38722. var i;
  38723. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  38724. var c;
  38725. if (faceColors) {
  38726. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  38727. }
  38728. // cap center
  38729. var vbase = positions.length / 3;
  38730. var offset = isTop ? height / 2 : -height / 2;
  38731. var center = new BABYLON.Vector3(0, offset, 0);
  38732. positions.push(center.x, center.y, center.z);
  38733. normals.push(0, isTop ? 1 : -1, 0);
  38734. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  38735. if (faceColors) {
  38736. colors.push(c.r, c.g, c.b, c.a);
  38737. }
  38738. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  38739. for (i = 0; i <= tessellation; i++) {
  38740. angle = Math.PI * 2 * i * arc / tessellation;
  38741. var cos = Math.cos(-angle);
  38742. var sin = Math.sin(-angle);
  38743. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  38744. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  38745. positions.push(circleVector.x, circleVector.y, circleVector.z);
  38746. normals.push(0, isTop ? 1 : -1, 0);
  38747. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  38748. if (faceColors) {
  38749. colors.push(c.r, c.g, c.b, c.a);
  38750. }
  38751. }
  38752. // Cap indices
  38753. for (i = 0; i < tessellation; i++) {
  38754. if (!isTop) {
  38755. indices.push(vbase);
  38756. indices.push(vbase + (i + 1));
  38757. indices.push(vbase + (i + 2));
  38758. }
  38759. else {
  38760. indices.push(vbase);
  38761. indices.push(vbase + (i + 2));
  38762. indices.push(vbase + (i + 1));
  38763. }
  38764. }
  38765. };
  38766. // add caps to geometry
  38767. createCylinderCap(false);
  38768. createCylinderCap(true);
  38769. // Sides
  38770. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38771. var vertexData = new VertexData();
  38772. vertexData.indices = indices;
  38773. vertexData.positions = positions;
  38774. vertexData.normals = normals;
  38775. vertexData.uvs = uvs;
  38776. if (faceColors) {
  38777. vertexData.colors = colors;
  38778. }
  38779. return vertexData;
  38780. };
  38781. /**
  38782. * Creates the VertexData of the Torus.
  38783. */
  38784. VertexData.CreateTorus = function (options) {
  38785. var indices = [];
  38786. var positions = [];
  38787. var normals = [];
  38788. var uvs = [];
  38789. var diameter = options.diameter || 1;
  38790. var thickness = options.thickness || 0.5;
  38791. var tessellation = options.tessellation || 16;
  38792. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38793. var stride = tessellation + 1;
  38794. for (var i = 0; i <= tessellation; i++) {
  38795. var u = i / tessellation;
  38796. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  38797. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  38798. for (var j = 0; j <= tessellation; j++) {
  38799. var v = 1 - j / tessellation;
  38800. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  38801. var dx = Math.cos(innerAngle);
  38802. var dy = Math.sin(innerAngle);
  38803. // Create a vertex.
  38804. var normal = new BABYLON.Vector3(dx, dy, 0);
  38805. var position = normal.scale(thickness / 2);
  38806. var textureCoordinate = new BABYLON.Vector2(u, v);
  38807. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  38808. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  38809. positions.push(position.x, position.y, position.z);
  38810. normals.push(normal.x, normal.y, normal.z);
  38811. uvs.push(textureCoordinate.x, textureCoordinate.y);
  38812. // And create indices for two triangles.
  38813. var nextI = (i + 1) % stride;
  38814. var nextJ = (j + 1) % stride;
  38815. indices.push(i * stride + j);
  38816. indices.push(i * stride + nextJ);
  38817. indices.push(nextI * stride + j);
  38818. indices.push(i * stride + nextJ);
  38819. indices.push(nextI * stride + nextJ);
  38820. indices.push(nextI * stride + j);
  38821. }
  38822. }
  38823. // Sides
  38824. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38825. // Result
  38826. var vertexData = new VertexData();
  38827. vertexData.indices = indices;
  38828. vertexData.positions = positions;
  38829. vertexData.normals = normals;
  38830. vertexData.uvs = uvs;
  38831. return vertexData;
  38832. };
  38833. /**
  38834. * Creates the VertexData of the LineSystem.
  38835. */
  38836. VertexData.CreateLineSystem = function (options) {
  38837. var indices = [];
  38838. var positions = [];
  38839. var lines = options.lines;
  38840. var idx = 0;
  38841. for (var l = 0; l < lines.length; l++) {
  38842. var points = lines[l];
  38843. for (var index = 0; index < points.length; index++) {
  38844. positions.push(points[index].x, points[index].y, points[index].z);
  38845. if (index > 0) {
  38846. indices.push(idx - 1);
  38847. indices.push(idx);
  38848. }
  38849. idx++;
  38850. }
  38851. }
  38852. var vertexData = new VertexData();
  38853. vertexData.indices = indices;
  38854. vertexData.positions = positions;
  38855. return vertexData;
  38856. };
  38857. /**
  38858. * Create the VertexData of the DashedLines.
  38859. */
  38860. VertexData.CreateDashedLines = function (options) {
  38861. var dashSize = options.dashSize || 3;
  38862. var gapSize = options.gapSize || 1;
  38863. var dashNb = options.dashNb || 200;
  38864. var points = options.points;
  38865. var positions = new Array();
  38866. var indices = new Array();
  38867. var curvect = BABYLON.Vector3.Zero();
  38868. var lg = 0;
  38869. var nb = 0;
  38870. var shft = 0;
  38871. var dashshft = 0;
  38872. var curshft = 0;
  38873. var idx = 0;
  38874. var i = 0;
  38875. for (i = 0; i < points.length - 1; i++) {
  38876. points[i + 1].subtractToRef(points[i], curvect);
  38877. lg += curvect.length();
  38878. }
  38879. shft = lg / dashNb;
  38880. dashshft = dashSize * shft / (dashSize + gapSize);
  38881. for (i = 0; i < points.length - 1; i++) {
  38882. points[i + 1].subtractToRef(points[i], curvect);
  38883. nb = Math.floor(curvect.length() / shft);
  38884. curvect.normalize();
  38885. for (var j = 0; j < nb; j++) {
  38886. curshft = shft * j;
  38887. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  38888. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  38889. indices.push(idx, idx + 1);
  38890. idx += 2;
  38891. }
  38892. }
  38893. // Result
  38894. var vertexData = new VertexData();
  38895. vertexData.positions = positions;
  38896. vertexData.indices = indices;
  38897. return vertexData;
  38898. };
  38899. /**
  38900. * Creates the VertexData of the Ground.
  38901. */
  38902. VertexData.CreateGround = function (options) {
  38903. var indices = [];
  38904. var positions = [];
  38905. var normals = [];
  38906. var uvs = [];
  38907. var row, col;
  38908. var width = options.width || 1;
  38909. var height = options.height || 1;
  38910. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  38911. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  38912. for (row = 0; row <= subdivisionsY; row++) {
  38913. for (col = 0; col <= subdivisionsX; col++) {
  38914. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  38915. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38916. positions.push(position.x, position.y, position.z);
  38917. normals.push(normal.x, normal.y, normal.z);
  38918. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  38919. }
  38920. }
  38921. for (row = 0; row < subdivisionsY; row++) {
  38922. for (col = 0; col < subdivisionsX; col++) {
  38923. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38924. indices.push(col + 1 + row * (subdivisionsX + 1));
  38925. indices.push(col + row * (subdivisionsX + 1));
  38926. indices.push(col + (row + 1) * (subdivisionsX + 1));
  38927. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38928. indices.push(col + row * (subdivisionsX + 1));
  38929. }
  38930. }
  38931. // Result
  38932. var vertexData = new VertexData();
  38933. vertexData.indices = indices;
  38934. vertexData.positions = positions;
  38935. vertexData.normals = normals;
  38936. vertexData.uvs = uvs;
  38937. return vertexData;
  38938. };
  38939. /**
  38940. * Creates the VertexData of the TiledGround.
  38941. */
  38942. VertexData.CreateTiledGround = function (options) {
  38943. var xmin = options.xmin || -1.0;
  38944. var zmin = options.zmin || -1.0;
  38945. var xmax = options.xmax || 1.0;
  38946. var zmax = options.zmax || 1.0;
  38947. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  38948. var precision = options.precision || { w: 1, h: 1 };
  38949. var indices = [];
  38950. var positions = [];
  38951. var normals = [];
  38952. var uvs = [];
  38953. var row, col, tileRow, tileCol;
  38954. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  38955. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  38956. precision.w = (precision.w < 1) ? 1 : precision.w;
  38957. precision.h = (precision.h < 1) ? 1 : precision.h;
  38958. var tileSize = {
  38959. 'w': (xmax - xmin) / subdivisions.w,
  38960. 'h': (zmax - zmin) / subdivisions.h
  38961. };
  38962. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  38963. // Indices
  38964. var base = positions.length / 3;
  38965. var rowLength = precision.w + 1;
  38966. for (row = 0; row < precision.h; row++) {
  38967. for (col = 0; col < precision.w; col++) {
  38968. var square = [
  38969. base + col + row * rowLength,
  38970. base + (col + 1) + row * rowLength,
  38971. base + (col + 1) + (row + 1) * rowLength,
  38972. base + col + (row + 1) * rowLength
  38973. ];
  38974. indices.push(square[1]);
  38975. indices.push(square[2]);
  38976. indices.push(square[3]);
  38977. indices.push(square[0]);
  38978. indices.push(square[1]);
  38979. indices.push(square[3]);
  38980. }
  38981. }
  38982. // Position, normals and uvs
  38983. var position = BABYLON.Vector3.Zero();
  38984. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38985. for (row = 0; row <= precision.h; row++) {
  38986. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  38987. for (col = 0; col <= precision.w; col++) {
  38988. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  38989. position.y = 0;
  38990. positions.push(position.x, position.y, position.z);
  38991. normals.push(normal.x, normal.y, normal.z);
  38992. uvs.push(col / precision.w, row / precision.h);
  38993. }
  38994. }
  38995. }
  38996. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  38997. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  38998. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  38999. }
  39000. }
  39001. // Result
  39002. var vertexData = new VertexData();
  39003. vertexData.indices = indices;
  39004. vertexData.positions = positions;
  39005. vertexData.normals = normals;
  39006. vertexData.uvs = uvs;
  39007. return vertexData;
  39008. };
  39009. /**
  39010. * Creates the VertexData of the Ground designed from a heightmap.
  39011. */
  39012. VertexData.CreateGroundFromHeightMap = function (options) {
  39013. var indices = [];
  39014. var positions = [];
  39015. var normals = [];
  39016. var uvs = [];
  39017. var row, col;
  39018. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39019. // Vertices
  39020. for (row = 0; row <= options.subdivisions; row++) {
  39021. for (col = 0; col <= options.subdivisions; col++) {
  39022. 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));
  39023. // Compute height
  39024. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  39025. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  39026. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  39027. var r = options.buffer[pos] / 255.0;
  39028. var g = options.buffer[pos + 1] / 255.0;
  39029. var b = options.buffer[pos + 2] / 255.0;
  39030. var gradient = r * filter.r + g * filter.g + b * filter.b;
  39031. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  39032. // Add vertex
  39033. positions.push(position.x, position.y, position.z);
  39034. normals.push(0, 0, 0);
  39035. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  39036. }
  39037. }
  39038. // Indices
  39039. for (row = 0; row < options.subdivisions; row++) {
  39040. for (col = 0; col < options.subdivisions; col++) {
  39041. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  39042. indices.push(col + 1 + row * (options.subdivisions + 1));
  39043. indices.push(col + row * (options.subdivisions + 1));
  39044. indices.push(col + (row + 1) * (options.subdivisions + 1));
  39045. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  39046. indices.push(col + row * (options.subdivisions + 1));
  39047. }
  39048. }
  39049. // Normals
  39050. VertexData.ComputeNormals(positions, indices, normals);
  39051. // Result
  39052. var vertexData = new VertexData();
  39053. vertexData.indices = indices;
  39054. vertexData.positions = positions;
  39055. vertexData.normals = normals;
  39056. vertexData.uvs = uvs;
  39057. return vertexData;
  39058. };
  39059. /**
  39060. * Creates the VertexData of the Plane.
  39061. */
  39062. VertexData.CreatePlane = function (options) {
  39063. var indices = [];
  39064. var positions = [];
  39065. var normals = [];
  39066. var uvs = [];
  39067. var width = options.width || options.size || 1;
  39068. var height = options.height || options.size || 1;
  39069. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39070. // Vertices
  39071. var halfWidth = width / 2.0;
  39072. var halfHeight = height / 2.0;
  39073. positions.push(-halfWidth, -halfHeight, 0);
  39074. normals.push(0, 0, -1.0);
  39075. uvs.push(0.0, 0.0);
  39076. positions.push(halfWidth, -halfHeight, 0);
  39077. normals.push(0, 0, -1.0);
  39078. uvs.push(1.0, 0.0);
  39079. positions.push(halfWidth, halfHeight, 0);
  39080. normals.push(0, 0, -1.0);
  39081. uvs.push(1.0, 1.0);
  39082. positions.push(-halfWidth, halfHeight, 0);
  39083. normals.push(0, 0, -1.0);
  39084. uvs.push(0.0, 1.0);
  39085. // Indices
  39086. indices.push(0);
  39087. indices.push(1);
  39088. indices.push(2);
  39089. indices.push(0);
  39090. indices.push(2);
  39091. indices.push(3);
  39092. // Sides
  39093. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39094. // Result
  39095. var vertexData = new VertexData();
  39096. vertexData.indices = indices;
  39097. vertexData.positions = positions;
  39098. vertexData.normals = normals;
  39099. vertexData.uvs = uvs;
  39100. return vertexData;
  39101. };
  39102. /**
  39103. * Creates the VertexData of the Disc or regular Polygon.
  39104. */
  39105. VertexData.CreateDisc = function (options) {
  39106. var positions = [];
  39107. var indices = [];
  39108. var normals = [];
  39109. var uvs = [];
  39110. var radius = options.radius || 0.5;
  39111. var tessellation = options.tessellation || 64;
  39112. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39113. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39114. // positions and uvs
  39115. positions.push(0, 0, 0); // disc center first
  39116. uvs.push(0.5, 0.5);
  39117. var theta = Math.PI * 2 * arc;
  39118. var step = theta / tessellation;
  39119. for (var a = 0; a < theta; a += step) {
  39120. var x = Math.cos(a);
  39121. var y = Math.sin(a);
  39122. var u = (x + 1) / 2;
  39123. var v = (1 - y) / 2;
  39124. positions.push(radius * x, radius * y, 0);
  39125. uvs.push(u, v);
  39126. }
  39127. if (arc === 1) {
  39128. positions.push(positions[3], positions[4], positions[5]); // close the circle
  39129. uvs.push(uvs[2], uvs[3]);
  39130. }
  39131. //indices
  39132. var vertexNb = positions.length / 3;
  39133. for (var i = 1; i < vertexNb - 1; i++) {
  39134. indices.push(i + 1, 0, i);
  39135. }
  39136. // result
  39137. VertexData.ComputeNormals(positions, indices, normals);
  39138. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39139. var vertexData = new VertexData();
  39140. vertexData.indices = indices;
  39141. vertexData.positions = positions;
  39142. vertexData.normals = normals;
  39143. vertexData.uvs = uvs;
  39144. return vertexData;
  39145. };
  39146. /**
  39147. * Creates the VertexData of the IcoSphere.
  39148. */
  39149. VertexData.CreateIcoSphere = function (options) {
  39150. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39151. var radius = options.radius || 1;
  39152. var flat = (options.flat === undefined) ? true : options.flat;
  39153. var subdivisions = options.subdivisions || 4;
  39154. var radiusX = options.radiusX || radius;
  39155. var radiusY = options.radiusY || radius;
  39156. var radiusZ = options.radiusZ || radius;
  39157. var t = (1 + Math.sqrt(5)) / 2;
  39158. // 12 vertex x,y,z
  39159. var ico_vertices = [
  39160. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  39161. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  39162. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  39163. ];
  39164. // index of 3 vertex makes a face of icopshere
  39165. var ico_indices = [
  39166. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  39167. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  39168. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  39169. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  39170. ];
  39171. // vertex for uv have aliased position, not for UV
  39172. var vertices_unalias_id = [
  39173. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  39174. // vertex alias
  39175. 0,
  39176. 2,
  39177. 3,
  39178. 3,
  39179. 3,
  39180. 4,
  39181. 7,
  39182. 8,
  39183. 9,
  39184. 9,
  39185. 10,
  39186. 11 // 23: B + 12
  39187. ];
  39188. // uv as integer step (not pixels !)
  39189. var ico_vertexuv = [
  39190. 5, 1, 3, 1, 6, 4, 0, 0,
  39191. 5, 3, 4, 2, 2, 2, 4, 0,
  39192. 2, 0, 1, 1, 6, 0, 6, 2,
  39193. // vertex alias (for same vertex on different faces)
  39194. 0, 4,
  39195. 3, 3,
  39196. 4, 4,
  39197. 3, 1,
  39198. 4, 2,
  39199. 4, 4,
  39200. 0, 2,
  39201. 1, 1,
  39202. 2, 2,
  39203. 3, 3,
  39204. 1, 3,
  39205. 2, 4 // 23: B + 12
  39206. ];
  39207. // Vertices[0, 1, ...9, A, B] : position on UV plane
  39208. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  39209. // First island of uv mapping
  39210. // v = 4h 3+ 2
  39211. // v = 3h 9+ 4
  39212. // v = 2h 9+ 5 B
  39213. // v = 1h 9 1 0
  39214. // v = 0h 3 8 7 A
  39215. // u = 0 1 2 3 4 5 6 *a
  39216. // Second island of uv mapping
  39217. // v = 4h 0+ B+ 4+
  39218. // v = 3h A+ 2+
  39219. // v = 2h 7+ 6 3+
  39220. // v = 1h 8+ 3+
  39221. // v = 0h
  39222. // u = 0 1 2 3 4 5 6 *a
  39223. // Face layout on texture UV mapping
  39224. // ============
  39225. // \ 4 /\ 16 / ======
  39226. // \ / \ / /\ 11 /
  39227. // \/ 7 \/ / \ /
  39228. // ======= / 10 \/
  39229. // /\ 17 /\ =======
  39230. // / \ / \ \ 15 /\
  39231. // / 8 \/ 12 \ \ / \
  39232. // ============ \/ 6 \
  39233. // \ 18 /\ ============
  39234. // \ / \ \ 5 /\ 0 /
  39235. // \/ 13 \ \ / \ /
  39236. // ======= \/ 1 \/
  39237. // =============
  39238. // /\ 19 /\ 2 /\
  39239. // / \ / \ / \
  39240. // / 14 \/ 9 \/ 3 \
  39241. // ===================
  39242. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  39243. var ustep = 138 / 1024;
  39244. var vstep = 239 / 1024;
  39245. var uoffset = 60 / 1024;
  39246. var voffset = 26 / 1024;
  39247. // Second island should have margin, not to touch the first island
  39248. // avoid any borderline artefact in pixel rounding
  39249. var island_u_offset = -40 / 1024;
  39250. var island_v_offset = +20 / 1024;
  39251. // face is either island 0 or 1 :
  39252. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  39253. var island = [
  39254. 0, 0, 0, 0, 1,
  39255. 0, 0, 1, 1, 0,
  39256. 0, 0, 1, 1, 0,
  39257. 0, 1, 1, 1, 0 // 15 - 19
  39258. ];
  39259. var indices = [];
  39260. var positions = [];
  39261. var normals = [];
  39262. var uvs = [];
  39263. var current_indice = 0;
  39264. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  39265. var face_vertex_pos = new Array(3);
  39266. var face_vertex_uv = new Array(3);
  39267. var v012;
  39268. for (v012 = 0; v012 < 3; v012++) {
  39269. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  39270. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  39271. }
  39272. // create all with normals
  39273. for (var face = 0; face < 20; face++) {
  39274. // 3 vertex per face
  39275. for (v012 = 0; v012 < 3; v012++) {
  39276. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  39277. var v_id = ico_indices[3 * face + v012];
  39278. // vertex have 3D position (x,y,z)
  39279. 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]);
  39280. // Normalize to get normal, then scale to radius
  39281. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  39282. // uv Coordinates from vertex ID
  39283. 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);
  39284. }
  39285. // Subdivide the face (interpolate pos, norm, uv)
  39286. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  39287. // - norm is linear interpolation of vertex corner normal
  39288. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  39289. // - uv is linear interpolation
  39290. //
  39291. // Topology is as below for sub-divide by 2
  39292. // vertex shown as v0,v1,v2
  39293. // interp index is i1 to progress in range [v0,v1[
  39294. // interp index is i2 to progress in range [v0,v2[
  39295. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  39296. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39297. //
  39298. //
  39299. // i2 v2
  39300. // ^ ^
  39301. // / / \
  39302. // / / \
  39303. // / / \
  39304. // / / (0,1) \
  39305. // / #---------\
  39306. // / / \ (0,0)'/ \
  39307. // / / \ / \
  39308. // / / \ / \
  39309. // / / (0,0) \ / (1,0) \
  39310. // / #---------#---------\
  39311. // v0 v1
  39312. //
  39313. // --------------------> i1
  39314. //
  39315. // interp of (i1,i2):
  39316. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  39317. // along i1 : lerp(x0,x1, i1/(S-i2))
  39318. //
  39319. // centroid of triangle is needed to get help normal computation
  39320. // (c1,c2) are used for centroid location
  39321. var interp_vertex = function (i1, i2, c1, c2) {
  39322. // vertex is interpolated from
  39323. // - face_vertex_pos[0..2]
  39324. // - face_vertex_uv[0..2]
  39325. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  39326. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  39327. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  39328. pos_interp.normalize();
  39329. var vertex_normal;
  39330. if (flat) {
  39331. // in flat mode, recalculate normal as face centroid normal
  39332. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  39333. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  39334. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  39335. }
  39336. else {
  39337. // in smooth mode, recalculate normal from each single vertex position
  39338. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  39339. }
  39340. // Vertex normal need correction due to X,Y,Z radius scaling
  39341. vertex_normal.x /= radiusX;
  39342. vertex_normal.y /= radiusY;
  39343. vertex_normal.z /= radiusZ;
  39344. vertex_normal.normalize();
  39345. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  39346. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  39347. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  39348. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  39349. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  39350. uvs.push(uv_interp.x, uv_interp.y);
  39351. // push each vertex has member of a face
  39352. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  39353. indices.push(current_indice);
  39354. current_indice++;
  39355. };
  39356. for (var i2 = 0; i2 < subdivisions; i2++) {
  39357. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  39358. // face : (i1,i2) for /\ :
  39359. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  39360. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39361. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39362. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39363. if (i1 + i2 + 1 < subdivisions) {
  39364. // face : (i1,i2)' for \/ :
  39365. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39366. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39367. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39368. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39369. }
  39370. }
  39371. }
  39372. }
  39373. // Sides
  39374. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39375. // Result
  39376. var vertexData = new VertexData();
  39377. vertexData.indices = indices;
  39378. vertexData.positions = positions;
  39379. vertexData.normals = normals;
  39380. vertexData.uvs = uvs;
  39381. return vertexData;
  39382. };
  39383. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  39384. /**
  39385. * Creates the VertexData of the Polyhedron.
  39386. */
  39387. VertexData.CreatePolyhedron = function (options) {
  39388. // provided polyhedron types :
  39389. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39390. // 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)
  39391. var polyhedra = [];
  39392. 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]] };
  39393. 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]] };
  39394. polyhedra[2] = {
  39395. 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]],
  39396. 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]]
  39397. };
  39398. polyhedra[3] = {
  39399. 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]],
  39400. 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]]
  39401. };
  39402. polyhedra[4] = {
  39403. 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]],
  39404. 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]]
  39405. };
  39406. 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]] };
  39407. 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]] };
  39408. 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]] };
  39409. 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]] };
  39410. 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]] };
  39411. 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]] };
  39412. 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]] };
  39413. 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]] };
  39414. 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]] };
  39415. polyhedra[14] = {
  39416. 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]],
  39417. 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]]
  39418. };
  39419. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  39420. var size = options.size;
  39421. var sizeX = options.sizeX || size || 1;
  39422. var sizeY = options.sizeY || size || 1;
  39423. var sizeZ = options.sizeZ || size || 1;
  39424. var data = options.custom || polyhedra[type];
  39425. var nbfaces = data.face.length;
  39426. var faceUV = options.faceUV || new Array(nbfaces);
  39427. var faceColors = options.faceColors;
  39428. var flat = (options.flat === undefined) ? true : options.flat;
  39429. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39430. var positions = [];
  39431. var indices = [];
  39432. var normals = [];
  39433. var uvs = [];
  39434. var colors = [];
  39435. var index = 0;
  39436. var faceIdx = 0; // face cursor in the array "indexes"
  39437. var indexes = [];
  39438. var i = 0;
  39439. var f = 0;
  39440. var u, v, ang, x, y, tmp;
  39441. // default face colors and UV if undefined
  39442. if (flat) {
  39443. for (f = 0; f < nbfaces; f++) {
  39444. if (faceColors && faceColors[f] === undefined) {
  39445. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39446. }
  39447. if (faceUV && faceUV[f] === undefined) {
  39448. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39449. }
  39450. }
  39451. }
  39452. if (!flat) {
  39453. for (i = 0; i < data.vertex.length; i++) {
  39454. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  39455. uvs.push(0, 0);
  39456. }
  39457. for (f = 0; f < nbfaces; f++) {
  39458. for (i = 0; i < data.face[f].length - 2; i++) {
  39459. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  39460. }
  39461. }
  39462. }
  39463. else {
  39464. for (f = 0; f < nbfaces; f++) {
  39465. var fl = data.face[f].length; // number of vertices of the current face
  39466. ang = 2 * Math.PI / fl;
  39467. x = 0.5 * Math.tan(ang / 2);
  39468. y = 0.5;
  39469. // positions, uvs, colors
  39470. for (i = 0; i < fl; i++) {
  39471. // positions
  39472. 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);
  39473. indexes.push(index);
  39474. index++;
  39475. // uvs
  39476. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  39477. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  39478. uvs.push(u, v);
  39479. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  39480. y = x * Math.sin(ang) + y * Math.cos(ang);
  39481. x = tmp;
  39482. // colors
  39483. if (faceColors) {
  39484. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  39485. }
  39486. }
  39487. // indices from indexes
  39488. for (i = 0; i < fl - 2; i++) {
  39489. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  39490. }
  39491. faceIdx += fl;
  39492. }
  39493. }
  39494. VertexData.ComputeNormals(positions, indices, normals);
  39495. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39496. var vertexData = new VertexData();
  39497. vertexData.positions = positions;
  39498. vertexData.indices = indices;
  39499. vertexData.normals = normals;
  39500. vertexData.uvs = uvs;
  39501. if (faceColors && flat) {
  39502. vertexData.colors = colors;
  39503. }
  39504. return vertexData;
  39505. };
  39506. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  39507. /**
  39508. * Creates the VertexData of the Torus Knot.
  39509. */
  39510. VertexData.CreateTorusKnot = function (options) {
  39511. var indices = [];
  39512. var positions = [];
  39513. var normals = [];
  39514. var uvs = [];
  39515. var radius = options.radius || 2;
  39516. var tube = options.tube || 0.5;
  39517. var radialSegments = options.radialSegments || 32;
  39518. var tubularSegments = options.tubularSegments || 32;
  39519. var p = options.p || 2;
  39520. var q = options.q || 3;
  39521. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39522. // Helper
  39523. var getPos = function (angle) {
  39524. var cu = Math.cos(angle);
  39525. var su = Math.sin(angle);
  39526. var quOverP = q / p * angle;
  39527. var cs = Math.cos(quOverP);
  39528. var tx = radius * (2 + cs) * 0.5 * cu;
  39529. var ty = radius * (2 + cs) * su * 0.5;
  39530. var tz = radius * Math.sin(quOverP) * 0.5;
  39531. return new BABYLON.Vector3(tx, ty, tz);
  39532. };
  39533. // Vertices
  39534. var i;
  39535. var j;
  39536. for (i = 0; i <= radialSegments; i++) {
  39537. var modI = i % radialSegments;
  39538. var u = modI / radialSegments * 2 * p * Math.PI;
  39539. var p1 = getPos(u);
  39540. var p2 = getPos(u + 0.01);
  39541. var tang = p2.subtract(p1);
  39542. var n = p2.add(p1);
  39543. var bitan = BABYLON.Vector3.Cross(tang, n);
  39544. n = BABYLON.Vector3.Cross(bitan, tang);
  39545. bitan.normalize();
  39546. n.normalize();
  39547. for (j = 0; j < tubularSegments; j++) {
  39548. var modJ = j % tubularSegments;
  39549. var v = modJ / tubularSegments * 2 * Math.PI;
  39550. var cx = -tube * Math.cos(v);
  39551. var cy = tube * Math.sin(v);
  39552. positions.push(p1.x + cx * n.x + cy * bitan.x);
  39553. positions.push(p1.y + cx * n.y + cy * bitan.y);
  39554. positions.push(p1.z + cx * n.z + cy * bitan.z);
  39555. uvs.push(i / radialSegments);
  39556. uvs.push(j / tubularSegments);
  39557. }
  39558. }
  39559. for (i = 0; i < radialSegments; i++) {
  39560. for (j = 0; j < tubularSegments; j++) {
  39561. var jNext = (j + 1) % tubularSegments;
  39562. var a = i * tubularSegments + j;
  39563. var b = (i + 1) * tubularSegments + j;
  39564. var c = (i + 1) * tubularSegments + jNext;
  39565. var d = i * tubularSegments + jNext;
  39566. indices.push(d);
  39567. indices.push(b);
  39568. indices.push(a);
  39569. indices.push(d);
  39570. indices.push(c);
  39571. indices.push(b);
  39572. }
  39573. }
  39574. // Normals
  39575. VertexData.ComputeNormals(positions, indices, normals);
  39576. // Sides
  39577. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39578. // Result
  39579. var vertexData = new VertexData();
  39580. vertexData.indices = indices;
  39581. vertexData.positions = positions;
  39582. vertexData.normals = normals;
  39583. vertexData.uvs = uvs;
  39584. return vertexData;
  39585. };
  39586. // Tools
  39587. /**
  39588. * @param {any} - positions (number[] or Float32Array)
  39589. * @param {any} - indices (number[] or Uint16Array)
  39590. * @param {any} - normals (number[] or Float32Array)
  39591. * options (optional) :
  39592. * facetPositions : optional array of facet positions (vector3)
  39593. * facetNormals : optional array of facet normals (vector3)
  39594. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  39595. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  39596. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  39597. * bbSize : optional bounding box size data, required for facetPartitioning computation
  39598. * bInfo : optional bounding info, required for facetPartitioning computation
  39599. */
  39600. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  39601. // temporary scalar variables
  39602. var index = 0; // facet index
  39603. var p1p2x = 0.0; // p1p2 vector x coordinate
  39604. var p1p2y = 0.0; // p1p2 vector y coordinate
  39605. var p1p2z = 0.0; // p1p2 vector z coordinate
  39606. var p3p2x = 0.0; // p3p2 vector x coordinate
  39607. var p3p2y = 0.0; // p3p2 vector y coordinate
  39608. var p3p2z = 0.0; // p3p2 vector z coordinate
  39609. var faceNormalx = 0.0; // facet normal x coordinate
  39610. var faceNormaly = 0.0; // facet normal y coordinate
  39611. var faceNormalz = 0.0; // facet normal z coordinate
  39612. var length = 0.0; // facet normal length before normalization
  39613. var v1x = 0; // vector1 x index in the positions array
  39614. var v1y = 0; // vector1 y index in the positions array
  39615. var v1z = 0; // vector1 z index in the positions array
  39616. var v2x = 0; // vector2 x index in the positions array
  39617. var v2y = 0; // vector2 y index in the positions array
  39618. var v2z = 0; // vector2 z index in the positions array
  39619. var v3x = 0; // vector3 x index in the positions array
  39620. var v3y = 0; // vector3 y index in the positions array
  39621. var v3z = 0; // vector3 z index in the positions array
  39622. var computeFacetNormals = false;
  39623. var computeFacetPositions = false;
  39624. var computeFacetPartitioning = false;
  39625. if (options) {
  39626. computeFacetNormals = (options.facetNormals) ? true : false;
  39627. computeFacetPositions = (options.facetPositions) ? true : false;
  39628. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  39629. }
  39630. // facetPartitioning reinit if needed
  39631. if (computeFacetPartitioning) {
  39632. var ox = 0; // X partitioning index for facet position
  39633. var oy = 0; // Y partinioning index for facet position
  39634. var oz = 0; // Z partinioning index for facet position
  39635. var b1x = 0; // X partitioning index for facet v1 vertex
  39636. var b1y = 0; // Y partitioning index for facet v1 vertex
  39637. var b1z = 0; // z partitioning index for facet v1 vertex
  39638. var b2x = 0; // X partitioning index for facet v2 vertex
  39639. var b2y = 0; // Y partitioning index for facet v2 vertex
  39640. var b2z = 0; // Z partitioning index for facet v2 vertex
  39641. var b3x = 0; // X partitioning index for facet v3 vertex
  39642. var b3y = 0; // Y partitioning index for facet v3 vertex
  39643. var b3z = 0; // Z partitioning index for facet v3 vertex
  39644. var block_idx_o = 0; // facet barycenter block index
  39645. var block_idx_v1 = 0; // v1 vertex block index
  39646. var block_idx_v2 = 0; // v2 vertex block index
  39647. var block_idx_v3 = 0; // v3 vertex block index
  39648. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  39649. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  39650. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  39651. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  39652. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  39653. var subSq = options.subDiv.max * options.subDiv.max;
  39654. options.facetPartitioning.length = 0;
  39655. }
  39656. // reset the normals
  39657. for (index = 0; index < positions.length; index++) {
  39658. normals[index] = 0.0;
  39659. }
  39660. // Loop : 1 indice triplet = 1 facet
  39661. var nbFaces = indices.length / 3;
  39662. for (index = 0; index < nbFaces; index++) {
  39663. // get the indexes of the coordinates of each vertex of the facet
  39664. v1x = indices[index * 3] * 3;
  39665. v1y = v1x + 1;
  39666. v1z = v1x + 2;
  39667. v2x = indices[index * 3 + 1] * 3;
  39668. v2y = v2x + 1;
  39669. v2z = v2x + 2;
  39670. v3x = indices[index * 3 + 2] * 3;
  39671. v3y = v3x + 1;
  39672. v3z = v3x + 2;
  39673. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  39674. p1p2y = positions[v1y] - positions[v2y];
  39675. p1p2z = positions[v1z] - positions[v2z];
  39676. p3p2x = positions[v3x] - positions[v2x];
  39677. p3p2y = positions[v3y] - positions[v2y];
  39678. p3p2z = positions[v3z] - positions[v2z];
  39679. // compute the face normal with the cross product
  39680. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  39681. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  39682. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  39683. // normalize this normal and store it in the array facetData
  39684. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39685. length = (length === 0) ? 1.0 : length;
  39686. faceNormalx /= length;
  39687. faceNormaly /= length;
  39688. faceNormalz /= length;
  39689. if (computeFacetNormals) {
  39690. options.facetNormals[index].x = faceNormalx;
  39691. options.facetNormals[index].y = faceNormaly;
  39692. options.facetNormals[index].z = faceNormalz;
  39693. }
  39694. if (computeFacetPositions) {
  39695. // compute and the facet barycenter coordinates in the array facetPositions
  39696. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  39697. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  39698. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  39699. }
  39700. if (computeFacetPartitioning) {
  39701. // store the facet indexes in arrays in the main facetPartitioning array :
  39702. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  39703. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  39704. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  39705. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  39706. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  39707. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  39708. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  39709. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  39710. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  39711. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  39712. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  39713. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  39714. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  39715. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  39716. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  39717. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  39718. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  39719. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  39720. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  39721. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  39722. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  39723. // push each facet index in each block containing the vertex
  39724. options.facetPartitioning[block_idx_v1].push(index);
  39725. if (block_idx_v2 != block_idx_v1) {
  39726. options.facetPartitioning[block_idx_v2].push(index);
  39727. }
  39728. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  39729. options.facetPartitioning[block_idx_v3].push(index);
  39730. }
  39731. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  39732. options.facetPartitioning[block_idx_o].push(index);
  39733. }
  39734. }
  39735. // compute the normals anyway
  39736. normals[v1x] += faceNormalx; // accumulate all the normals per face
  39737. normals[v1y] += faceNormaly;
  39738. normals[v1z] += faceNormalz;
  39739. normals[v2x] += faceNormalx;
  39740. normals[v2y] += faceNormaly;
  39741. normals[v2z] += faceNormalz;
  39742. normals[v3x] += faceNormalx;
  39743. normals[v3y] += faceNormaly;
  39744. normals[v3z] += faceNormalz;
  39745. }
  39746. // last normalization of each normal
  39747. for (index = 0; index < normals.length / 3; index++) {
  39748. faceNormalx = normals[index * 3];
  39749. faceNormaly = normals[index * 3 + 1];
  39750. faceNormalz = normals[index * 3 + 2];
  39751. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39752. length = (length === 0) ? 1.0 : length;
  39753. faceNormalx /= length;
  39754. faceNormaly /= length;
  39755. faceNormalz /= length;
  39756. normals[index * 3] = faceNormalx;
  39757. normals[index * 3 + 1] = faceNormaly;
  39758. normals[index * 3 + 2] = faceNormalz;
  39759. }
  39760. };
  39761. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  39762. var li = indices.length;
  39763. var ln = normals.length;
  39764. var i;
  39765. var n;
  39766. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39767. switch (sideOrientation) {
  39768. case BABYLON.Mesh.FRONTSIDE:
  39769. // nothing changed
  39770. break;
  39771. case BABYLON.Mesh.BACKSIDE:
  39772. var tmp;
  39773. // indices
  39774. for (i = 0; i < li; i += 3) {
  39775. tmp = indices[i];
  39776. indices[i] = indices[i + 2];
  39777. indices[i + 2] = tmp;
  39778. }
  39779. // normals
  39780. for (n = 0; n < ln; n++) {
  39781. normals[n] = -normals[n];
  39782. }
  39783. break;
  39784. case BABYLON.Mesh.DOUBLESIDE:
  39785. // positions
  39786. var lp = positions.length;
  39787. var l = lp / 3;
  39788. for (var p = 0; p < lp; p++) {
  39789. positions[lp + p] = positions[p];
  39790. }
  39791. // indices
  39792. for (i = 0; i < li; i += 3) {
  39793. indices[i + li] = indices[i + 2] + l;
  39794. indices[i + 1 + li] = indices[i + 1] + l;
  39795. indices[i + 2 + li] = indices[i] + l;
  39796. }
  39797. // normals
  39798. for (n = 0; n < ln; n++) {
  39799. normals[ln + n] = -normals[n];
  39800. }
  39801. // uvs
  39802. var lu = uvs.length;
  39803. for (var u = 0; u < lu; u++) {
  39804. uvs[u + lu] = uvs[u];
  39805. }
  39806. break;
  39807. }
  39808. };
  39809. /**
  39810. * Creates a new VertexData from the imported parameters.
  39811. */
  39812. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  39813. var vertexData = new VertexData();
  39814. // positions
  39815. var positions = parsedVertexData.positions;
  39816. if (positions) {
  39817. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  39818. }
  39819. // normals
  39820. var normals = parsedVertexData.normals;
  39821. if (normals) {
  39822. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  39823. }
  39824. // tangents
  39825. var tangents = parsedVertexData.tangents;
  39826. if (tangents) {
  39827. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  39828. }
  39829. // uvs
  39830. var uvs = parsedVertexData.uvs;
  39831. if (uvs) {
  39832. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  39833. }
  39834. // uv2s
  39835. var uv2s = parsedVertexData.uv2s;
  39836. if (uv2s) {
  39837. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  39838. }
  39839. // uv3s
  39840. var uv3s = parsedVertexData.uv3s;
  39841. if (uv3s) {
  39842. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39843. }
  39844. // uv4s
  39845. var uv4s = parsedVertexData.uv4s;
  39846. if (uv4s) {
  39847. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39848. }
  39849. // uv5s
  39850. var uv5s = parsedVertexData.uv5s;
  39851. if (uv5s) {
  39852. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39853. }
  39854. // uv6s
  39855. var uv6s = parsedVertexData.uv6s;
  39856. if (uv6s) {
  39857. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39858. }
  39859. // colors
  39860. var colors = parsedVertexData.colors;
  39861. if (colors) {
  39862. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39863. }
  39864. // matricesIndices
  39865. var matricesIndices = parsedVertexData.matricesIndices;
  39866. if (matricesIndices) {
  39867. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39868. }
  39869. // matricesWeights
  39870. var matricesWeights = parsedVertexData.matricesWeights;
  39871. if (matricesWeights) {
  39872. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39873. }
  39874. // indices
  39875. var indices = parsedVertexData.indices;
  39876. if (indices) {
  39877. vertexData.indices = indices;
  39878. }
  39879. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39880. };
  39881. return VertexData;
  39882. }());
  39883. BABYLON.VertexData = VertexData;
  39884. })(BABYLON || (BABYLON = {}));
  39885. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39886. var BABYLON;
  39887. (function (BABYLON) {
  39888. var Tags = (function () {
  39889. function Tags() {
  39890. }
  39891. Tags.EnableFor = function (obj) {
  39892. obj._tags = obj._tags || {};
  39893. obj.hasTags = function () {
  39894. return Tags.HasTags(obj);
  39895. };
  39896. obj.addTags = function (tagsString) {
  39897. return Tags.AddTagsTo(obj, tagsString);
  39898. };
  39899. obj.removeTags = function (tagsString) {
  39900. return Tags.RemoveTagsFrom(obj, tagsString);
  39901. };
  39902. obj.matchesTagsQuery = function (tagsQuery) {
  39903. return Tags.MatchesQuery(obj, tagsQuery);
  39904. };
  39905. };
  39906. Tags.DisableFor = function (obj) {
  39907. delete obj._tags;
  39908. delete obj.hasTags;
  39909. delete obj.addTags;
  39910. delete obj.removeTags;
  39911. delete obj.matchesTagsQuery;
  39912. };
  39913. Tags.HasTags = function (obj) {
  39914. if (!obj._tags) {
  39915. return false;
  39916. }
  39917. return !BABYLON.Tools.IsEmpty(obj._tags);
  39918. };
  39919. Tags.GetTags = function (obj, asString) {
  39920. if (asString === void 0) { asString = true; }
  39921. if (!obj._tags) {
  39922. return null;
  39923. }
  39924. if (asString) {
  39925. var tagsArray = [];
  39926. for (var tag in obj._tags) {
  39927. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  39928. tagsArray.push(tag);
  39929. }
  39930. }
  39931. return tagsArray.join(" ");
  39932. }
  39933. else {
  39934. return obj._tags;
  39935. }
  39936. };
  39937. // the tags 'true' and 'false' are reserved and cannot be used as tags
  39938. // a tag cannot start with '||', '&&', and '!'
  39939. // it cannot contain whitespaces
  39940. Tags.AddTagsTo = function (obj, tagsString) {
  39941. if (!tagsString) {
  39942. return;
  39943. }
  39944. if (typeof tagsString !== "string") {
  39945. return;
  39946. }
  39947. var tags = tagsString.split(" ");
  39948. tags.forEach(function (tag, index, array) {
  39949. Tags._AddTagTo(obj, tag);
  39950. });
  39951. };
  39952. Tags._AddTagTo = function (obj, tag) {
  39953. tag = tag.trim();
  39954. if (tag === "" || tag === "true" || tag === "false") {
  39955. return;
  39956. }
  39957. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  39958. return;
  39959. }
  39960. Tags.EnableFor(obj);
  39961. obj._tags[tag] = true;
  39962. };
  39963. Tags.RemoveTagsFrom = function (obj, tagsString) {
  39964. if (!Tags.HasTags(obj)) {
  39965. return;
  39966. }
  39967. var tags = tagsString.split(" ");
  39968. for (var t in tags) {
  39969. Tags._RemoveTagFrom(obj, tags[t]);
  39970. }
  39971. };
  39972. Tags._RemoveTagFrom = function (obj, tag) {
  39973. delete obj._tags[tag];
  39974. };
  39975. Tags.MatchesQuery = function (obj, tagsQuery) {
  39976. if (tagsQuery === undefined) {
  39977. return true;
  39978. }
  39979. if (tagsQuery === "") {
  39980. return Tags.HasTags(obj);
  39981. }
  39982. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  39983. };
  39984. return Tags;
  39985. }());
  39986. BABYLON.Tags = Tags;
  39987. })(BABYLON || (BABYLON = {}));
  39988. //# sourceMappingURL=babylon.tags.js.map
  39989. var BABYLON;
  39990. (function (BABYLON) {
  39991. var Internals;
  39992. (function (Internals) {
  39993. var AndOrNotEvaluator = (function () {
  39994. function AndOrNotEvaluator() {
  39995. }
  39996. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  39997. if (!query.match(/\([^\(\)]*\)/g)) {
  39998. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  39999. }
  40000. else {
  40001. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  40002. // remove parenthesis
  40003. r = r.slice(1, r.length - 1);
  40004. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  40005. });
  40006. }
  40007. if (query === "true") {
  40008. return true;
  40009. }
  40010. if (query === "false") {
  40011. return false;
  40012. }
  40013. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  40014. };
  40015. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  40016. evaluateCallback = evaluateCallback || (function (r) {
  40017. return r === "true" ? true : false;
  40018. });
  40019. var result;
  40020. var or = parenthesisContent.split("||");
  40021. for (var i in or) {
  40022. if (or.hasOwnProperty(i)) {
  40023. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  40024. var and = ori.split("&&");
  40025. if (and.length > 1) {
  40026. for (var j = 0; j < and.length; ++j) {
  40027. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  40028. if (andj !== "true" && andj !== "false") {
  40029. if (andj[0] === "!") {
  40030. result = !evaluateCallback(andj.substring(1));
  40031. }
  40032. else {
  40033. result = evaluateCallback(andj);
  40034. }
  40035. }
  40036. else {
  40037. result = andj === "true" ? true : false;
  40038. }
  40039. if (!result) {
  40040. ori = "false";
  40041. break;
  40042. }
  40043. }
  40044. }
  40045. if (result || ori === "true") {
  40046. result = true;
  40047. break;
  40048. }
  40049. // result equals false (or undefined)
  40050. if (ori !== "true" && ori !== "false") {
  40051. if (ori[0] === "!") {
  40052. result = !evaluateCallback(ori.substring(1));
  40053. }
  40054. else {
  40055. result = evaluateCallback(ori);
  40056. }
  40057. }
  40058. else {
  40059. result = ori === "true" ? true : false;
  40060. }
  40061. }
  40062. }
  40063. // the whole parenthesis scope is replaced by 'true' or 'false'
  40064. return result ? "true" : "false";
  40065. };
  40066. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  40067. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  40068. // remove whitespaces
  40069. r = r.replace(/[\s]/g, function () { return ""; });
  40070. return r.length % 2 ? "!" : "";
  40071. });
  40072. booleanString = booleanString.trim();
  40073. if (booleanString === "!true") {
  40074. booleanString = "false";
  40075. }
  40076. else if (booleanString === "!false") {
  40077. booleanString = "true";
  40078. }
  40079. return booleanString;
  40080. };
  40081. return AndOrNotEvaluator;
  40082. }());
  40083. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  40084. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40085. })(BABYLON || (BABYLON = {}));
  40086. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  40087. var BABYLON;
  40088. (function (BABYLON) {
  40089. var PostProcessRenderPass = (function () {
  40090. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  40091. this._enabled = true;
  40092. this._refCount = 0;
  40093. this._name = name;
  40094. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  40095. this.setRenderList(renderList);
  40096. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  40097. this._renderTexture.onAfterRenderObservable.add(afterRender);
  40098. this._scene = scene;
  40099. this._renderList = renderList;
  40100. }
  40101. // private
  40102. PostProcessRenderPass.prototype._incRefCount = function () {
  40103. if (this._refCount === 0) {
  40104. this._scene.customRenderTargets.push(this._renderTexture);
  40105. }
  40106. return ++this._refCount;
  40107. };
  40108. PostProcessRenderPass.prototype._decRefCount = function () {
  40109. this._refCount--;
  40110. if (this._refCount <= 0) {
  40111. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  40112. }
  40113. return this._refCount;
  40114. };
  40115. PostProcessRenderPass.prototype._update = function () {
  40116. this.setRenderList(this._renderList);
  40117. };
  40118. // public
  40119. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  40120. this._renderTexture.renderList = renderList;
  40121. };
  40122. PostProcessRenderPass.prototype.getRenderTexture = function () {
  40123. return this._renderTexture;
  40124. };
  40125. return PostProcessRenderPass;
  40126. }());
  40127. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  40128. })(BABYLON || (BABYLON = {}));
  40129. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  40130. var BABYLON;
  40131. (function (BABYLON) {
  40132. var PostProcessRenderEffect = (function () {
  40133. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  40134. this._engine = engine;
  40135. this._name = name;
  40136. this._singleInstance = singleInstance || true;
  40137. this._getPostProcess = getPostProcess;
  40138. this._cameras = [];
  40139. this._indicesForCamera = [];
  40140. this._postProcesses = {};
  40141. this._renderPasses = {};
  40142. this._renderEffectAsPasses = {};
  40143. }
  40144. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  40145. get: function () {
  40146. for (var index in this._postProcesses) {
  40147. if (!this._postProcesses[index].isSupported) {
  40148. return false;
  40149. }
  40150. }
  40151. return true;
  40152. },
  40153. enumerable: true,
  40154. configurable: true
  40155. });
  40156. PostProcessRenderEffect.prototype._update = function () {
  40157. for (var renderPassName in this._renderPasses) {
  40158. this._renderPasses[renderPassName]._update();
  40159. }
  40160. };
  40161. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  40162. this._renderPasses[renderPass._name] = renderPass;
  40163. this._linkParameters();
  40164. };
  40165. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  40166. delete this._renderPasses[renderPass._name];
  40167. this._linkParameters();
  40168. };
  40169. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  40170. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  40171. this._linkParameters();
  40172. };
  40173. PostProcessRenderEffect.prototype.getPass = function (passName) {
  40174. for (var renderPassName in this._renderPasses) {
  40175. if (renderPassName === passName) {
  40176. return this._renderPasses[passName];
  40177. }
  40178. }
  40179. };
  40180. PostProcessRenderEffect.prototype.emptyPasses = function () {
  40181. this._renderPasses = {};
  40182. this._linkParameters();
  40183. };
  40184. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  40185. var cameraKey;
  40186. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40187. for (var i = 0; i < _cam.length; i++) {
  40188. var camera = _cam[i];
  40189. var cameraName = camera.name;
  40190. if (this._singleInstance) {
  40191. cameraKey = 0;
  40192. }
  40193. else {
  40194. cameraKey = cameraName;
  40195. }
  40196. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  40197. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  40198. if (!this._indicesForCamera[cameraName]) {
  40199. this._indicesForCamera[cameraName] = [];
  40200. }
  40201. this._indicesForCamera[cameraName].push(index);
  40202. if (this._cameras.indexOf(camera) === -1) {
  40203. this._cameras[cameraName] = camera;
  40204. }
  40205. for (var passName in this._renderPasses) {
  40206. this._renderPasses[passName]._incRefCount();
  40207. }
  40208. }
  40209. this._linkParameters();
  40210. };
  40211. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  40212. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40213. for (var i = 0; i < _cam.length; i++) {
  40214. var camera = _cam[i];
  40215. var cameraName = camera.name;
  40216. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  40217. var index = this._cameras.indexOf(cameraName);
  40218. this._indicesForCamera.splice(index, 1);
  40219. this._cameras.splice(index, 1);
  40220. for (var passName in this._renderPasses) {
  40221. this._renderPasses[passName]._decRefCount();
  40222. }
  40223. }
  40224. };
  40225. PostProcessRenderEffect.prototype._enable = function (cameras) {
  40226. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40227. for (var i = 0; i < _cam.length; i++) {
  40228. var camera = _cam[i];
  40229. var cameraName = camera.name;
  40230. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  40231. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  40232. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  40233. }
  40234. }
  40235. for (var passName in this._renderPasses) {
  40236. this._renderPasses[passName]._incRefCount();
  40237. }
  40238. }
  40239. };
  40240. PostProcessRenderEffect.prototype._disable = function (cameras) {
  40241. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40242. for (var i = 0; i < _cam.length; i++) {
  40243. var camera = _cam[i];
  40244. var cameraName = camera.Name;
  40245. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  40246. for (var passName in this._renderPasses) {
  40247. this._renderPasses[passName]._decRefCount();
  40248. }
  40249. }
  40250. };
  40251. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  40252. if (this._singleInstance) {
  40253. return this._postProcesses[0];
  40254. }
  40255. else {
  40256. return this._postProcesses[camera.name];
  40257. }
  40258. };
  40259. PostProcessRenderEffect.prototype._linkParameters = function () {
  40260. var _this = this;
  40261. for (var index in this._postProcesses) {
  40262. if (this.applyParameters) {
  40263. this.applyParameters(this._postProcesses[index]);
  40264. }
  40265. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  40266. _this._linkTextures(effect);
  40267. });
  40268. }
  40269. };
  40270. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  40271. for (var renderPassName in this._renderPasses) {
  40272. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  40273. }
  40274. for (var renderEffectName in this._renderEffectAsPasses) {
  40275. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  40276. }
  40277. };
  40278. return PostProcessRenderEffect;
  40279. }());
  40280. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  40281. })(BABYLON || (BABYLON = {}));
  40282. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  40283. var BABYLON;
  40284. (function (BABYLON) {
  40285. var PostProcessRenderPipeline = (function () {
  40286. function PostProcessRenderPipeline(engine, name) {
  40287. this._engine = engine;
  40288. this._name = name;
  40289. this._renderEffects = {};
  40290. this._renderEffectsForIsolatedPass = {};
  40291. this._cameras = [];
  40292. }
  40293. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  40294. get: function () {
  40295. for (var renderEffectName in this._renderEffects) {
  40296. if (!this._renderEffects[renderEffectName].isSupported) {
  40297. return false;
  40298. }
  40299. }
  40300. return true;
  40301. },
  40302. enumerable: true,
  40303. configurable: true
  40304. });
  40305. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  40306. this._renderEffects[renderEffect._name] = renderEffect;
  40307. };
  40308. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  40309. var renderEffects = this._renderEffects[renderEffectName];
  40310. if (!renderEffects) {
  40311. return;
  40312. }
  40313. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  40314. };
  40315. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  40316. var renderEffects = this._renderEffects[renderEffectName];
  40317. if (!renderEffects) {
  40318. return;
  40319. }
  40320. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  40321. };
  40322. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  40323. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40324. var indicesToDelete = [];
  40325. var i;
  40326. for (i = 0; i < _cam.length; i++) {
  40327. var camera = _cam[i];
  40328. var cameraName = camera.name;
  40329. if (this._cameras.indexOf(camera) === -1) {
  40330. this._cameras[cameraName] = camera;
  40331. }
  40332. else if (unique) {
  40333. indicesToDelete.push(i);
  40334. }
  40335. }
  40336. for (i = 0; i < indicesToDelete.length; i++) {
  40337. cameras.splice(indicesToDelete[i], 1);
  40338. }
  40339. for (var renderEffectName in this._renderEffects) {
  40340. this._renderEffects[renderEffectName]._attachCameras(_cam);
  40341. }
  40342. };
  40343. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  40344. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40345. for (var renderEffectName in this._renderEffects) {
  40346. this._renderEffects[renderEffectName]._detachCameras(_cam);
  40347. }
  40348. for (var i = 0; i < _cam.length; i++) {
  40349. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  40350. }
  40351. };
  40352. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  40353. var _this = this;
  40354. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40355. var pass = null;
  40356. var renderEffectName;
  40357. for (renderEffectName in this._renderEffects) {
  40358. pass = this._renderEffects[renderEffectName].getPass(passName);
  40359. if (pass != null) {
  40360. break;
  40361. }
  40362. }
  40363. if (pass === null) {
  40364. return;
  40365. }
  40366. for (renderEffectName in this._renderEffects) {
  40367. this._renderEffects[renderEffectName]._disable(_cam);
  40368. }
  40369. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  40370. for (var i = 0; i < _cam.length; i++) {
  40371. var camera = _cam[i];
  40372. var cameraName = camera.name;
  40373. 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); });
  40374. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  40375. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  40376. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  40377. }
  40378. };
  40379. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  40380. var _this = this;
  40381. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40382. for (var i = 0; i < _cam.length; i++) {
  40383. var camera = _cam[i];
  40384. var cameraName = camera.name;
  40385. 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); });
  40386. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  40387. }
  40388. for (var renderEffectName in this._renderEffects) {
  40389. this._renderEffects[renderEffectName]._enable(_cam);
  40390. }
  40391. };
  40392. PostProcessRenderPipeline.prototype._update = function () {
  40393. for (var renderEffectName in this._renderEffects) {
  40394. this._renderEffects[renderEffectName]._update();
  40395. }
  40396. for (var i = 0; i < this._cameras.length; i++) {
  40397. var cameraName = this._cameras[i].name;
  40398. if (this._renderEffectsForIsolatedPass[cameraName]) {
  40399. this._renderEffectsForIsolatedPass[cameraName]._update();
  40400. }
  40401. }
  40402. };
  40403. PostProcessRenderPipeline.prototype.dispose = function () {
  40404. // Must be implemented by children
  40405. };
  40406. return PostProcessRenderPipeline;
  40407. }());
  40408. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  40409. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  40410. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  40411. })(BABYLON || (BABYLON = {}));
  40412. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  40413. var BABYLON;
  40414. (function (BABYLON) {
  40415. var PostProcessRenderPipelineManager = (function () {
  40416. function PostProcessRenderPipelineManager() {
  40417. this._renderPipelines = {};
  40418. }
  40419. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  40420. this._renderPipelines[renderPipeline._name] = renderPipeline;
  40421. };
  40422. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  40423. var renderPipeline = this._renderPipelines[renderPipelineName];
  40424. if (!renderPipeline) {
  40425. return;
  40426. }
  40427. renderPipeline._attachCameras(cameras, unique);
  40428. };
  40429. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  40430. var renderPipeline = this._renderPipelines[renderPipelineName];
  40431. if (!renderPipeline) {
  40432. return;
  40433. }
  40434. renderPipeline._detachCameras(cameras);
  40435. };
  40436. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  40437. var renderPipeline = this._renderPipelines[renderPipelineName];
  40438. if (!renderPipeline) {
  40439. return;
  40440. }
  40441. renderPipeline._enableEffect(renderEffectName, cameras);
  40442. };
  40443. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  40444. var renderPipeline = this._renderPipelines[renderPipelineName];
  40445. if (!renderPipeline) {
  40446. return;
  40447. }
  40448. renderPipeline._disableEffect(renderEffectName, cameras);
  40449. };
  40450. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  40451. var renderPipeline = this._renderPipelines[renderPipelineName];
  40452. if (!renderPipeline) {
  40453. return;
  40454. }
  40455. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  40456. };
  40457. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  40458. var renderPipeline = this._renderPipelines[renderPipelineName];
  40459. if (!renderPipeline) {
  40460. return;
  40461. }
  40462. renderPipeline._disableDisplayOnlyPass(cameras);
  40463. };
  40464. PostProcessRenderPipelineManager.prototype.update = function () {
  40465. for (var renderPipelineName in this._renderPipelines) {
  40466. var pipeline = this._renderPipelines[renderPipelineName];
  40467. if (!pipeline.isSupported) {
  40468. pipeline.dispose();
  40469. delete this._renderPipelines[renderPipelineName];
  40470. }
  40471. else {
  40472. pipeline._update();
  40473. }
  40474. }
  40475. };
  40476. return PostProcessRenderPipelineManager;
  40477. }());
  40478. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  40479. })(BABYLON || (BABYLON = {}));
  40480. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  40481. var BABYLON;
  40482. (function (BABYLON) {
  40483. var BoundingBoxRenderer = (function () {
  40484. function BoundingBoxRenderer(scene) {
  40485. this.frontColor = new BABYLON.Color3(1, 1, 1);
  40486. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  40487. this.showBackLines = true;
  40488. this.renderList = new BABYLON.SmartArray(32);
  40489. this._vertexBuffers = {};
  40490. this._scene = scene;
  40491. }
  40492. BoundingBoxRenderer.prototype._prepareRessources = function () {
  40493. if (this._colorShader) {
  40494. return;
  40495. }
  40496. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  40497. attributes: [BABYLON.VertexBuffer.PositionKind],
  40498. uniforms: ["worldViewProjection", "color"]
  40499. });
  40500. var engine = this._scene.getEngine();
  40501. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  40502. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  40503. 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]);
  40504. };
  40505. BoundingBoxRenderer.prototype.reset = function () {
  40506. this.renderList.reset();
  40507. };
  40508. BoundingBoxRenderer.prototype.render = function () {
  40509. if (this.renderList.length === 0) {
  40510. return;
  40511. }
  40512. this._prepareRessources();
  40513. if (!this._colorShader.isReady()) {
  40514. return;
  40515. }
  40516. var engine = this._scene.getEngine();
  40517. engine.setDepthWrite(false);
  40518. this._colorShader._preBind();
  40519. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  40520. var boundingBox = this.renderList.data[boundingBoxIndex];
  40521. var min = boundingBox.minimum;
  40522. var max = boundingBox.maximum;
  40523. var diff = max.subtract(min);
  40524. var median = min.add(diff.scale(0.5));
  40525. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  40526. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  40527. .multiply(boundingBox.getWorldMatrix());
  40528. // VBOs
  40529. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  40530. if (this.showBackLines) {
  40531. // Back
  40532. engine.setDepthFunctionToGreaterOrEqual();
  40533. this._scene.resetCachedMaterial();
  40534. this._colorShader.setColor4("color", this.backColor.toColor4());
  40535. this._colorShader.bind(worldMatrix);
  40536. // Draw order
  40537. engine.draw(false, 0, 24);
  40538. }
  40539. // Front
  40540. engine.setDepthFunctionToLess();
  40541. this._scene.resetCachedMaterial();
  40542. this._colorShader.setColor4("color", this.frontColor.toColor4());
  40543. this._colorShader.bind(worldMatrix);
  40544. // Draw order
  40545. engine.draw(false, 0, 24);
  40546. }
  40547. this._colorShader.unbind();
  40548. engine.setDepthFunctionToLessOrEqual();
  40549. engine.setDepthWrite(true);
  40550. };
  40551. BoundingBoxRenderer.prototype.dispose = function () {
  40552. if (!this._colorShader) {
  40553. return;
  40554. }
  40555. this.renderList.dispose();
  40556. this._colorShader.dispose();
  40557. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40558. if (buffer) {
  40559. buffer.dispose();
  40560. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40561. }
  40562. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40563. };
  40564. return BoundingBoxRenderer;
  40565. }());
  40566. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  40567. })(BABYLON || (BABYLON = {}));
  40568. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  40569. var BABYLON;
  40570. (function (BABYLON) {
  40571. var Condition = (function () {
  40572. function Condition(actionManager) {
  40573. this._actionManager = actionManager;
  40574. }
  40575. Condition.prototype.isValid = function () {
  40576. return true;
  40577. };
  40578. Condition.prototype._getProperty = function (propertyPath) {
  40579. return this._actionManager._getProperty(propertyPath);
  40580. };
  40581. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  40582. return this._actionManager._getEffectiveTarget(target, propertyPath);
  40583. };
  40584. Condition.prototype.serialize = function () {
  40585. };
  40586. Condition.prototype._serialize = function (serializedCondition) {
  40587. return {
  40588. type: 2,
  40589. children: [],
  40590. name: serializedCondition.name,
  40591. properties: serializedCondition.properties
  40592. };
  40593. };
  40594. return Condition;
  40595. }());
  40596. BABYLON.Condition = Condition;
  40597. var ValueCondition = (function (_super) {
  40598. __extends(ValueCondition, _super);
  40599. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  40600. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  40601. var _this = _super.call(this, actionManager) || this;
  40602. _this.propertyPath = propertyPath;
  40603. _this.value = value;
  40604. _this.operator = operator;
  40605. _this._target = target;
  40606. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  40607. _this._property = _this._getProperty(_this.propertyPath);
  40608. return _this;
  40609. }
  40610. Object.defineProperty(ValueCondition, "IsEqual", {
  40611. get: function () {
  40612. return ValueCondition._IsEqual;
  40613. },
  40614. enumerable: true,
  40615. configurable: true
  40616. });
  40617. Object.defineProperty(ValueCondition, "IsDifferent", {
  40618. get: function () {
  40619. return ValueCondition._IsDifferent;
  40620. },
  40621. enumerable: true,
  40622. configurable: true
  40623. });
  40624. Object.defineProperty(ValueCondition, "IsGreater", {
  40625. get: function () {
  40626. return ValueCondition._IsGreater;
  40627. },
  40628. enumerable: true,
  40629. configurable: true
  40630. });
  40631. Object.defineProperty(ValueCondition, "IsLesser", {
  40632. get: function () {
  40633. return ValueCondition._IsLesser;
  40634. },
  40635. enumerable: true,
  40636. configurable: true
  40637. });
  40638. // Methods
  40639. ValueCondition.prototype.isValid = function () {
  40640. switch (this.operator) {
  40641. case ValueCondition.IsGreater:
  40642. return this._effectiveTarget[this._property] > this.value;
  40643. case ValueCondition.IsLesser:
  40644. return this._effectiveTarget[this._property] < this.value;
  40645. case ValueCondition.IsEqual:
  40646. case ValueCondition.IsDifferent:
  40647. var check;
  40648. if (this.value.equals) {
  40649. check = this.value.equals(this._effectiveTarget[this._property]);
  40650. }
  40651. else {
  40652. check = this.value === this._effectiveTarget[this._property];
  40653. }
  40654. return this.operator === ValueCondition.IsEqual ? check : !check;
  40655. }
  40656. return false;
  40657. };
  40658. ValueCondition.prototype.serialize = function () {
  40659. return this._serialize({
  40660. name: "ValueCondition",
  40661. properties: [
  40662. BABYLON.Action._GetTargetProperty(this._target),
  40663. { name: "propertyPath", value: this.propertyPath },
  40664. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  40665. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  40666. ]
  40667. });
  40668. };
  40669. ValueCondition.GetOperatorName = function (operator) {
  40670. switch (operator) {
  40671. case ValueCondition._IsEqual: return "IsEqual";
  40672. case ValueCondition._IsDifferent: return "IsDifferent";
  40673. case ValueCondition._IsGreater: return "IsGreater";
  40674. case ValueCondition._IsLesser: return "IsLesser";
  40675. default: return "";
  40676. }
  40677. };
  40678. return ValueCondition;
  40679. }(Condition));
  40680. // Statics
  40681. ValueCondition._IsEqual = 0;
  40682. ValueCondition._IsDifferent = 1;
  40683. ValueCondition._IsGreater = 2;
  40684. ValueCondition._IsLesser = 3;
  40685. BABYLON.ValueCondition = ValueCondition;
  40686. var PredicateCondition = (function (_super) {
  40687. __extends(PredicateCondition, _super);
  40688. function PredicateCondition(actionManager, predicate) {
  40689. var _this = _super.call(this, actionManager) || this;
  40690. _this.predicate = predicate;
  40691. return _this;
  40692. }
  40693. PredicateCondition.prototype.isValid = function () {
  40694. return this.predicate();
  40695. };
  40696. return PredicateCondition;
  40697. }(Condition));
  40698. BABYLON.PredicateCondition = PredicateCondition;
  40699. var StateCondition = (function (_super) {
  40700. __extends(StateCondition, _super);
  40701. function StateCondition(actionManager, target, value) {
  40702. var _this = _super.call(this, actionManager) || this;
  40703. _this.value = value;
  40704. _this._target = target;
  40705. return _this;
  40706. }
  40707. // Methods
  40708. StateCondition.prototype.isValid = function () {
  40709. return this._target.state === this.value;
  40710. };
  40711. StateCondition.prototype.serialize = function () {
  40712. return this._serialize({
  40713. name: "StateCondition",
  40714. properties: [
  40715. BABYLON.Action._GetTargetProperty(this._target),
  40716. { name: "value", value: this.value }
  40717. ]
  40718. });
  40719. };
  40720. return StateCondition;
  40721. }(Condition));
  40722. BABYLON.StateCondition = StateCondition;
  40723. })(BABYLON || (BABYLON = {}));
  40724. //# sourceMappingURL=babylon.condition.js.map
  40725. var BABYLON;
  40726. (function (BABYLON) {
  40727. var Action = (function () {
  40728. function Action(triggerOptions, condition) {
  40729. this.triggerOptions = triggerOptions;
  40730. if (triggerOptions.parameter) {
  40731. this.trigger = triggerOptions.trigger;
  40732. this._triggerParameter = triggerOptions.parameter;
  40733. }
  40734. else {
  40735. this.trigger = triggerOptions;
  40736. }
  40737. this._nextActiveAction = this;
  40738. this._condition = condition;
  40739. }
  40740. // Methods
  40741. Action.prototype._prepare = function () {
  40742. };
  40743. Action.prototype.getTriggerParameter = function () {
  40744. return this._triggerParameter;
  40745. };
  40746. Action.prototype._executeCurrent = function (evt) {
  40747. if (this._nextActiveAction._condition) {
  40748. var condition = this._nextActiveAction._condition;
  40749. var currentRenderId = this._actionManager.getScene().getRenderId();
  40750. // We cache the current evaluation for the current frame
  40751. if (condition._evaluationId === currentRenderId) {
  40752. if (!condition._currentResult) {
  40753. return;
  40754. }
  40755. }
  40756. else {
  40757. condition._evaluationId = currentRenderId;
  40758. if (!condition.isValid()) {
  40759. condition._currentResult = false;
  40760. return;
  40761. }
  40762. condition._currentResult = true;
  40763. }
  40764. }
  40765. this._nextActiveAction.execute(evt);
  40766. this.skipToNextActiveAction();
  40767. };
  40768. Action.prototype.execute = function (evt) {
  40769. };
  40770. Action.prototype.skipToNextActiveAction = function () {
  40771. if (this._nextActiveAction._child) {
  40772. if (!this._nextActiveAction._child._actionManager) {
  40773. this._nextActiveAction._child._actionManager = this._actionManager;
  40774. }
  40775. this._nextActiveAction = this._nextActiveAction._child;
  40776. }
  40777. else {
  40778. this._nextActiveAction = this;
  40779. }
  40780. };
  40781. Action.prototype.then = function (action) {
  40782. this._child = action;
  40783. action._actionManager = this._actionManager;
  40784. action._prepare();
  40785. return action;
  40786. };
  40787. Action.prototype._getProperty = function (propertyPath) {
  40788. return this._actionManager._getProperty(propertyPath);
  40789. };
  40790. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  40791. return this._actionManager._getEffectiveTarget(target, propertyPath);
  40792. };
  40793. Action.prototype.serialize = function (parent) {
  40794. };
  40795. // Called by BABYLON.Action objects in serialize(...). Internal use
  40796. Action.prototype._serialize = function (serializedAction, parent) {
  40797. var serializationObject = {
  40798. type: 1,
  40799. children: [],
  40800. name: serializedAction.name,
  40801. properties: serializedAction.properties || []
  40802. };
  40803. // Serialize child
  40804. if (this._child) {
  40805. this._child.serialize(serializationObject);
  40806. }
  40807. // Check if "this" has a condition
  40808. if (this._condition) {
  40809. var serializedCondition = this._condition.serialize();
  40810. serializedCondition.children.push(serializationObject);
  40811. if (parent) {
  40812. parent.children.push(serializedCondition);
  40813. }
  40814. return serializedCondition;
  40815. }
  40816. if (parent) {
  40817. parent.children.push(serializationObject);
  40818. }
  40819. return serializationObject;
  40820. };
  40821. return Action;
  40822. }());
  40823. Action._SerializeValueAsString = function (value) {
  40824. if (typeof value === "number") {
  40825. return value.toString();
  40826. }
  40827. if (typeof value === "boolean") {
  40828. return value ? "true" : "false";
  40829. }
  40830. if (value instanceof BABYLON.Vector2) {
  40831. return value.x + ", " + value.y;
  40832. }
  40833. if (value instanceof BABYLON.Vector3) {
  40834. return value.x + ", " + value.y + ", " + value.z;
  40835. }
  40836. if (value instanceof BABYLON.Color3) {
  40837. return value.r + ", " + value.g + ", " + value.b;
  40838. }
  40839. if (value instanceof BABYLON.Color4) {
  40840. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  40841. }
  40842. return value; // string
  40843. };
  40844. Action._GetTargetProperty = function (target) {
  40845. return {
  40846. name: "target",
  40847. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  40848. : target instanceof BABYLON.Light ? "LightProperties"
  40849. : target instanceof BABYLON.Camera ? "CameraProperties"
  40850. : "SceneProperties",
  40851. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  40852. };
  40853. };
  40854. BABYLON.Action = Action;
  40855. })(BABYLON || (BABYLON = {}));
  40856. //# sourceMappingURL=babylon.action.js.map
  40857. var BABYLON;
  40858. (function (BABYLON) {
  40859. /**
  40860. * ActionEvent is the event beint sent when an action is triggered.
  40861. */
  40862. var ActionEvent = (function () {
  40863. /**
  40864. * @constructor
  40865. * @param source The mesh or sprite that triggered the action.
  40866. * @param pointerX The X mouse cursor position at the time of the event
  40867. * @param pointerY The Y mouse cursor position at the time of the event
  40868. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  40869. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  40870. */
  40871. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  40872. this.source = source;
  40873. this.pointerX = pointerX;
  40874. this.pointerY = pointerY;
  40875. this.meshUnderPointer = meshUnderPointer;
  40876. this.sourceEvent = sourceEvent;
  40877. this.additionalData = additionalData;
  40878. }
  40879. /**
  40880. * Helper function to auto-create an ActionEvent from a source mesh.
  40881. * @param source The source mesh that triggered the event
  40882. * @param evt {Event} The original (browser) event
  40883. */
  40884. ActionEvent.CreateNew = function (source, evt, additionalData) {
  40885. var scene = source.getScene();
  40886. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  40887. };
  40888. /**
  40889. * Helper function to auto-create an ActionEvent from a source mesh.
  40890. * @param source The source sprite that triggered the event
  40891. * @param scene Scene associated with the sprite
  40892. * @param evt {Event} The original (browser) event
  40893. */
  40894. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  40895. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  40896. };
  40897. /**
  40898. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  40899. * @param scene the scene where the event occurred
  40900. * @param evt {Event} The original (browser) event
  40901. */
  40902. ActionEvent.CreateNewFromScene = function (scene, evt) {
  40903. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  40904. };
  40905. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  40906. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  40907. };
  40908. return ActionEvent;
  40909. }());
  40910. BABYLON.ActionEvent = ActionEvent;
  40911. /**
  40912. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  40913. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  40914. */
  40915. var ActionManager = (function () {
  40916. function ActionManager(scene) {
  40917. // Members
  40918. this.actions = new Array();
  40919. this.hoverCursor = '';
  40920. this._scene = scene;
  40921. scene._actionManagers.push(this);
  40922. }
  40923. Object.defineProperty(ActionManager, "NothingTrigger", {
  40924. get: function () {
  40925. return ActionManager._NothingTrigger;
  40926. },
  40927. enumerable: true,
  40928. configurable: true
  40929. });
  40930. Object.defineProperty(ActionManager, "OnPickTrigger", {
  40931. get: function () {
  40932. return ActionManager._OnPickTrigger;
  40933. },
  40934. enumerable: true,
  40935. configurable: true
  40936. });
  40937. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  40938. get: function () {
  40939. return ActionManager._OnLeftPickTrigger;
  40940. },
  40941. enumerable: true,
  40942. configurable: true
  40943. });
  40944. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  40945. get: function () {
  40946. return ActionManager._OnRightPickTrigger;
  40947. },
  40948. enumerable: true,
  40949. configurable: true
  40950. });
  40951. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  40952. get: function () {
  40953. return ActionManager._OnCenterPickTrigger;
  40954. },
  40955. enumerable: true,
  40956. configurable: true
  40957. });
  40958. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  40959. get: function () {
  40960. return ActionManager._OnPickDownTrigger;
  40961. },
  40962. enumerable: true,
  40963. configurable: true
  40964. });
  40965. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  40966. get: function () {
  40967. return ActionManager._OnDoublePickTrigger;
  40968. },
  40969. enumerable: true,
  40970. configurable: true
  40971. });
  40972. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  40973. get: function () {
  40974. return ActionManager._OnPickUpTrigger;
  40975. },
  40976. enumerable: true,
  40977. configurable: true
  40978. });
  40979. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  40980. /// This trigger will only be raised if you also declared a OnPickDown
  40981. get: function () {
  40982. return ActionManager._OnPickOutTrigger;
  40983. },
  40984. enumerable: true,
  40985. configurable: true
  40986. });
  40987. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  40988. get: function () {
  40989. return ActionManager._OnLongPressTrigger;
  40990. },
  40991. enumerable: true,
  40992. configurable: true
  40993. });
  40994. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  40995. get: function () {
  40996. return ActionManager._OnPointerOverTrigger;
  40997. },
  40998. enumerable: true,
  40999. configurable: true
  41000. });
  41001. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  41002. get: function () {
  41003. return ActionManager._OnPointerOutTrigger;
  41004. },
  41005. enumerable: true,
  41006. configurable: true
  41007. });
  41008. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  41009. get: function () {
  41010. return ActionManager._OnEveryFrameTrigger;
  41011. },
  41012. enumerable: true,
  41013. configurable: true
  41014. });
  41015. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  41016. get: function () {
  41017. return ActionManager._OnIntersectionEnterTrigger;
  41018. },
  41019. enumerable: true,
  41020. configurable: true
  41021. });
  41022. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  41023. get: function () {
  41024. return ActionManager._OnIntersectionExitTrigger;
  41025. },
  41026. enumerable: true,
  41027. configurable: true
  41028. });
  41029. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  41030. get: function () {
  41031. return ActionManager._OnKeyDownTrigger;
  41032. },
  41033. enumerable: true,
  41034. configurable: true
  41035. });
  41036. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  41037. get: function () {
  41038. return ActionManager._OnKeyUpTrigger;
  41039. },
  41040. enumerable: true,
  41041. configurable: true
  41042. });
  41043. // Methods
  41044. ActionManager.prototype.dispose = function () {
  41045. var index = this._scene._actionManagers.indexOf(this);
  41046. for (var i = 0; i < this.actions.length; i++) {
  41047. var action = this.actions[i];
  41048. ActionManager.Triggers[action.trigger]--;
  41049. if (ActionManager.Triggers[action.trigger] === 0) {
  41050. delete ActionManager.Triggers[action.trigger];
  41051. }
  41052. }
  41053. if (index > -1) {
  41054. this._scene._actionManagers.splice(index, 1);
  41055. }
  41056. };
  41057. ActionManager.prototype.getScene = function () {
  41058. return this._scene;
  41059. };
  41060. /**
  41061. * Does this action manager handles actions of any of the given triggers
  41062. * @param {number[]} triggers - the triggers to be tested
  41063. * @return {boolean} whether one (or more) of the triggers is handeled
  41064. */
  41065. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  41066. for (var index = 0; index < this.actions.length; index++) {
  41067. var action = this.actions[index];
  41068. if (triggers.indexOf(action.trigger) > -1) {
  41069. return true;
  41070. }
  41071. }
  41072. return false;
  41073. };
  41074. /**
  41075. * Does this action manager handles actions of a given trigger
  41076. * @param {number} trigger - the trigger to be tested
  41077. * @return {boolean} whether the trigger is handeled
  41078. */
  41079. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  41080. for (var index = 0; index < this.actions.length; index++) {
  41081. var action = this.actions[index];
  41082. if (action.trigger === trigger) {
  41083. return true;
  41084. }
  41085. }
  41086. return false;
  41087. };
  41088. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  41089. /**
  41090. * Does this action manager has pointer triggers
  41091. * @return {boolean} whether or not it has pointer triggers
  41092. */
  41093. get: function () {
  41094. for (var index = 0; index < this.actions.length; index++) {
  41095. var action = this.actions[index];
  41096. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  41097. return true;
  41098. }
  41099. }
  41100. return false;
  41101. },
  41102. enumerable: true,
  41103. configurable: true
  41104. });
  41105. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  41106. /**
  41107. * Does this action manager has pick triggers
  41108. * @return {boolean} whether or not it has pick triggers
  41109. */
  41110. get: function () {
  41111. for (var index = 0; index < this.actions.length; index++) {
  41112. var action = this.actions[index];
  41113. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  41114. return true;
  41115. }
  41116. }
  41117. return false;
  41118. },
  41119. enumerable: true,
  41120. configurable: true
  41121. });
  41122. Object.defineProperty(ActionManager, "HasTriggers", {
  41123. /**
  41124. * Does exist one action manager with at least one trigger
  41125. * @return {boolean} whether or not it exists one action manager with one trigger
  41126. **/
  41127. get: function () {
  41128. for (var t in ActionManager.Triggers) {
  41129. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41130. return true;
  41131. }
  41132. }
  41133. return false;
  41134. },
  41135. enumerable: true,
  41136. configurable: true
  41137. });
  41138. Object.defineProperty(ActionManager, "HasPickTriggers", {
  41139. /**
  41140. * Does exist one action manager with at least one pick trigger
  41141. * @return {boolean} whether or not it exists one action manager with one pick trigger
  41142. **/
  41143. get: function () {
  41144. for (var t in ActionManager.Triggers) {
  41145. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41146. var t_int = parseInt(t);
  41147. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  41148. return true;
  41149. }
  41150. }
  41151. }
  41152. return false;
  41153. },
  41154. enumerable: true,
  41155. configurable: true
  41156. });
  41157. /**
  41158. * Does exist one action manager that handles actions of a given trigger
  41159. * @param {number} trigger - the trigger to be tested
  41160. * @return {boolean} whether the trigger is handeled by at least one action manager
  41161. **/
  41162. ActionManager.HasSpecificTrigger = function (trigger) {
  41163. for (var t in ActionManager.Triggers) {
  41164. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41165. var t_int = parseInt(t);
  41166. if (t_int === trigger) {
  41167. return true;
  41168. }
  41169. }
  41170. }
  41171. return false;
  41172. };
  41173. /**
  41174. * Registers an action to this action manager
  41175. * @param {BABYLON.Action} action - the action to be registered
  41176. * @return {BABYLON.Action} the action amended (prepared) after registration
  41177. */
  41178. ActionManager.prototype.registerAction = function (action) {
  41179. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  41180. if (this.getScene().actionManager !== this) {
  41181. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  41182. return null;
  41183. }
  41184. }
  41185. this.actions.push(action);
  41186. if (ActionManager.Triggers[action.trigger]) {
  41187. ActionManager.Triggers[action.trigger]++;
  41188. }
  41189. else {
  41190. ActionManager.Triggers[action.trigger] = 1;
  41191. }
  41192. action._actionManager = this;
  41193. action._prepare();
  41194. return action;
  41195. };
  41196. /**
  41197. * Process a specific trigger
  41198. * @param {number} trigger - the trigger to process
  41199. * @param evt {BABYLON.ActionEvent} the event details to be processed
  41200. */
  41201. ActionManager.prototype.processTrigger = function (trigger, evt) {
  41202. for (var index = 0; index < this.actions.length; index++) {
  41203. var action = this.actions[index];
  41204. if (action.trigger === trigger) {
  41205. if (trigger === ActionManager.OnKeyUpTrigger
  41206. || trigger === ActionManager.OnKeyDownTrigger) {
  41207. var parameter = action.getTriggerParameter();
  41208. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  41209. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  41210. var actualkey = String.fromCharCode(unicode).toLowerCase();
  41211. if (actualkey !== parameter.toLowerCase()) {
  41212. continue;
  41213. }
  41214. }
  41215. }
  41216. action._executeCurrent(evt);
  41217. }
  41218. }
  41219. };
  41220. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  41221. var properties = propertyPath.split(".");
  41222. for (var index = 0; index < properties.length - 1; index++) {
  41223. target = target[properties[index]];
  41224. }
  41225. return target;
  41226. };
  41227. ActionManager.prototype._getProperty = function (propertyPath) {
  41228. var properties = propertyPath.split(".");
  41229. return properties[properties.length - 1];
  41230. };
  41231. ActionManager.prototype.serialize = function (name) {
  41232. var root = {
  41233. children: [],
  41234. name: name,
  41235. type: 3,
  41236. properties: [] // Empty for root but required
  41237. };
  41238. for (var i = 0; i < this.actions.length; i++) {
  41239. var triggerObject = {
  41240. type: 0,
  41241. children: [],
  41242. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  41243. properties: []
  41244. };
  41245. var triggerOptions = this.actions[i].triggerOptions;
  41246. if (triggerOptions && typeof triggerOptions !== "number") {
  41247. if (triggerOptions.parameter instanceof BABYLON.Node) {
  41248. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  41249. }
  41250. else {
  41251. var parameter = {};
  41252. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  41253. if (triggerOptions.parameter.mesh) {
  41254. parameter._meshId = triggerOptions.parameter.mesh.id;
  41255. }
  41256. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  41257. }
  41258. }
  41259. // Serialize child action, recursively
  41260. this.actions[i].serialize(triggerObject);
  41261. // Add serialized trigger
  41262. root.children.push(triggerObject);
  41263. }
  41264. return root;
  41265. };
  41266. ActionManager.Parse = function (parsedActions, object, scene) {
  41267. var actionManager = new BABYLON.ActionManager(scene);
  41268. if (object === null)
  41269. scene.actionManager = actionManager;
  41270. else
  41271. object.actionManager = actionManager;
  41272. // instanciate a new object
  41273. var instanciate = function (name, params) {
  41274. var newInstance = Object.create(BABYLON[name].prototype);
  41275. newInstance.constructor.apply(newInstance, params);
  41276. return newInstance;
  41277. };
  41278. var parseParameter = function (name, value, target, propertyPath) {
  41279. if (propertyPath === null) {
  41280. // String, boolean or float
  41281. var floatValue = parseFloat(value);
  41282. if (value === "true" || value === "false")
  41283. return value === "true";
  41284. else
  41285. return isNaN(floatValue) ? value : floatValue;
  41286. }
  41287. var effectiveTarget = propertyPath.split(".");
  41288. var values = value.split(",");
  41289. // Get effective Target
  41290. for (var i = 0; i < effectiveTarget.length; i++) {
  41291. target = target[effectiveTarget[i]];
  41292. }
  41293. // Return appropriate value with its type
  41294. if (typeof (target) === "boolean")
  41295. return values[0] === "true";
  41296. if (typeof (target) === "string")
  41297. return values[0];
  41298. // Parameters with multiple values such as Vector3 etc.
  41299. var split = new Array();
  41300. for (var i = 0; i < values.length; i++)
  41301. split.push(parseFloat(values[i]));
  41302. if (target instanceof BABYLON.Vector3)
  41303. return BABYLON.Vector3.FromArray(split);
  41304. if (target instanceof BABYLON.Vector4)
  41305. return BABYLON.Vector4.FromArray(split);
  41306. if (target instanceof BABYLON.Color3)
  41307. return BABYLON.Color3.FromArray(split);
  41308. if (target instanceof BABYLON.Color4)
  41309. return BABYLON.Color4.FromArray(split);
  41310. return parseFloat(values[0]);
  41311. };
  41312. // traverse graph per trigger
  41313. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  41314. if (combineArray === void 0) { combineArray = null; }
  41315. if (parsedAction.detached)
  41316. return;
  41317. var parameters = new Array();
  41318. var target = null;
  41319. var propertyPath = null;
  41320. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  41321. // Parameters
  41322. if (parsedAction.type === 2)
  41323. parameters.push(actionManager);
  41324. else
  41325. parameters.push(trigger);
  41326. if (combine) {
  41327. var actions = new Array();
  41328. for (var j = 0; j < parsedAction.combine.length; j++) {
  41329. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  41330. }
  41331. parameters.push(actions);
  41332. }
  41333. else {
  41334. for (var i = 0; i < parsedAction.properties.length; i++) {
  41335. var value = parsedAction.properties[i].value;
  41336. var name = parsedAction.properties[i].name;
  41337. var targetType = parsedAction.properties[i].targetType;
  41338. if (name === "target")
  41339. if (targetType !== null && targetType === "SceneProperties")
  41340. value = target = scene;
  41341. else
  41342. value = target = scene.getNodeByName(value);
  41343. else if (name === "parent")
  41344. value = scene.getNodeByName(value);
  41345. else if (name === "sound")
  41346. value = scene.getSoundByName(value);
  41347. else if (name !== "propertyPath") {
  41348. if (parsedAction.type === 2 && name === "operator")
  41349. value = BABYLON.ValueCondition[value];
  41350. else
  41351. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  41352. }
  41353. else {
  41354. propertyPath = value;
  41355. }
  41356. parameters.push(value);
  41357. }
  41358. }
  41359. if (combineArray === null) {
  41360. parameters.push(condition);
  41361. }
  41362. else {
  41363. parameters.push(null);
  41364. }
  41365. // If interpolate value action
  41366. if (parsedAction.name === "InterpolateValueAction") {
  41367. var param = parameters[parameters.length - 2];
  41368. parameters[parameters.length - 1] = param;
  41369. parameters[parameters.length - 2] = condition;
  41370. }
  41371. // Action or condition(s) and not CombineAction
  41372. var newAction = instanciate(parsedAction.name, parameters);
  41373. if (newAction instanceof BABYLON.Condition && condition !== null) {
  41374. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  41375. if (action)
  41376. action.then(nothing);
  41377. else
  41378. actionManager.registerAction(nothing);
  41379. action = nothing;
  41380. }
  41381. if (combineArray === null) {
  41382. if (newAction instanceof BABYLON.Condition) {
  41383. condition = newAction;
  41384. newAction = action;
  41385. }
  41386. else {
  41387. condition = null;
  41388. if (action)
  41389. action.then(newAction);
  41390. else
  41391. actionManager.registerAction(newAction);
  41392. }
  41393. }
  41394. else {
  41395. combineArray.push(newAction);
  41396. }
  41397. for (var i = 0; i < parsedAction.children.length; i++)
  41398. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  41399. };
  41400. // triggers
  41401. for (var i = 0; i < parsedActions.children.length; i++) {
  41402. var triggerParams;
  41403. var trigger = parsedActions.children[i];
  41404. if (trigger.properties.length > 0) {
  41405. var param = trigger.properties[0].value;
  41406. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  41407. if (value._meshId) {
  41408. value.mesh = scene.getMeshByID(value._meshId);
  41409. }
  41410. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  41411. }
  41412. else
  41413. triggerParams = BABYLON.ActionManager[trigger.name];
  41414. for (var j = 0; j < trigger.children.length; j++) {
  41415. if (!trigger.detached)
  41416. traverse(trigger.children[j], triggerParams, null, null);
  41417. }
  41418. }
  41419. };
  41420. ActionManager.GetTriggerName = function (trigger) {
  41421. switch (trigger) {
  41422. case 0: return "NothingTrigger";
  41423. case 1: return "OnPickTrigger";
  41424. case 2: return "OnLeftPickTrigger";
  41425. case 3: return "OnRightPickTrigger";
  41426. case 4: return "OnCenterPickTrigger";
  41427. case 5: return "OnPickDownTrigger";
  41428. case 6: return "OnPickUpTrigger";
  41429. case 7: return "OnLongPressTrigger";
  41430. case 8: return "OnPointerOverTrigger";
  41431. case 9: return "OnPointerOutTrigger";
  41432. case 10: return "OnEveryFrameTrigger";
  41433. case 11: return "OnIntersectionEnterTrigger";
  41434. case 12: return "OnIntersectionExitTrigger";
  41435. case 13: return "OnKeyDownTrigger";
  41436. case 14: return "OnKeyUpTrigger";
  41437. case 15: return "OnPickOutTrigger";
  41438. default: return "";
  41439. }
  41440. };
  41441. return ActionManager;
  41442. }());
  41443. // Statics
  41444. ActionManager._NothingTrigger = 0;
  41445. ActionManager._OnPickTrigger = 1;
  41446. ActionManager._OnLeftPickTrigger = 2;
  41447. ActionManager._OnRightPickTrigger = 3;
  41448. ActionManager._OnCenterPickTrigger = 4;
  41449. ActionManager._OnPickDownTrigger = 5;
  41450. ActionManager._OnDoublePickTrigger = 6;
  41451. ActionManager._OnPickUpTrigger = 7;
  41452. ActionManager._OnLongPressTrigger = 8;
  41453. ActionManager._OnPointerOverTrigger = 9;
  41454. ActionManager._OnPointerOutTrigger = 10;
  41455. ActionManager._OnEveryFrameTrigger = 11;
  41456. ActionManager._OnIntersectionEnterTrigger = 12;
  41457. ActionManager._OnIntersectionExitTrigger = 13;
  41458. ActionManager._OnKeyDownTrigger = 14;
  41459. ActionManager._OnKeyUpTrigger = 15;
  41460. ActionManager._OnPickOutTrigger = 16;
  41461. ActionManager.Triggers = {};
  41462. BABYLON.ActionManager = ActionManager;
  41463. })(BABYLON || (BABYLON = {}));
  41464. //# sourceMappingURL=babylon.actionManager.js.map
  41465. var BABYLON;
  41466. (function (BABYLON) {
  41467. var InterpolateValueAction = (function (_super) {
  41468. __extends(InterpolateValueAction, _super);
  41469. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  41470. if (duration === void 0) { duration = 1000; }
  41471. var _this = _super.call(this, triggerOptions, condition) || this;
  41472. _this.propertyPath = propertyPath;
  41473. _this.value = value;
  41474. _this.duration = duration;
  41475. _this.stopOtherAnimations = stopOtherAnimations;
  41476. _this.onInterpolationDone = onInterpolationDone;
  41477. _this._target = _this._effectiveTarget = target;
  41478. return _this;
  41479. }
  41480. InterpolateValueAction.prototype._prepare = function () {
  41481. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  41482. this._property = this._getProperty(this.propertyPath);
  41483. };
  41484. InterpolateValueAction.prototype.execute = function () {
  41485. var scene = this._actionManager.getScene();
  41486. var keys = [
  41487. {
  41488. frame: 0,
  41489. value: this._effectiveTarget[this._property]
  41490. }, {
  41491. frame: 100,
  41492. value: this.value
  41493. }
  41494. ];
  41495. var dataType;
  41496. if (typeof this.value === "number") {
  41497. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  41498. }
  41499. else if (this.value instanceof BABYLON.Color3) {
  41500. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  41501. }
  41502. else if (this.value instanceof BABYLON.Vector3) {
  41503. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  41504. }
  41505. else if (this.value instanceof BABYLON.Matrix) {
  41506. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  41507. }
  41508. else if (this.value instanceof BABYLON.Quaternion) {
  41509. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  41510. }
  41511. else {
  41512. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  41513. return;
  41514. }
  41515. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  41516. animation.setKeys(keys);
  41517. if (this.stopOtherAnimations) {
  41518. scene.stopAnimation(this._effectiveTarget);
  41519. }
  41520. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  41521. };
  41522. InterpolateValueAction.prototype.serialize = function (parent) {
  41523. return _super.prototype._serialize.call(this, {
  41524. name: "InterpolateValueAction",
  41525. properties: [
  41526. BABYLON.Action._GetTargetProperty(this._target),
  41527. { name: "propertyPath", value: this.propertyPath },
  41528. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41529. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  41530. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  41531. ]
  41532. }, parent);
  41533. };
  41534. return InterpolateValueAction;
  41535. }(BABYLON.Action));
  41536. BABYLON.InterpolateValueAction = InterpolateValueAction;
  41537. })(BABYLON || (BABYLON = {}));
  41538. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  41539. var BABYLON;
  41540. (function (BABYLON) {
  41541. var SwitchBooleanAction = (function (_super) {
  41542. __extends(SwitchBooleanAction, _super);
  41543. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  41544. var _this = _super.call(this, triggerOptions, condition) || this;
  41545. _this.propertyPath = propertyPath;
  41546. _this._target = _this._effectiveTarget = target;
  41547. return _this;
  41548. }
  41549. SwitchBooleanAction.prototype._prepare = function () {
  41550. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  41551. this._property = this._getProperty(this.propertyPath);
  41552. };
  41553. SwitchBooleanAction.prototype.execute = function () {
  41554. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  41555. };
  41556. SwitchBooleanAction.prototype.serialize = function (parent) {
  41557. return _super.prototype._serialize.call(this, {
  41558. name: "SwitchBooleanAction",
  41559. properties: [
  41560. BABYLON.Action._GetTargetProperty(this._target),
  41561. { name: "propertyPath", value: this.propertyPath }
  41562. ]
  41563. }, parent);
  41564. };
  41565. return SwitchBooleanAction;
  41566. }(BABYLON.Action));
  41567. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  41568. var SetStateAction = (function (_super) {
  41569. __extends(SetStateAction, _super);
  41570. function SetStateAction(triggerOptions, target, value, condition) {
  41571. var _this = _super.call(this, triggerOptions, condition) || this;
  41572. _this.value = value;
  41573. _this._target = target;
  41574. return _this;
  41575. }
  41576. SetStateAction.prototype.execute = function () {
  41577. this._target.state = this.value;
  41578. };
  41579. SetStateAction.prototype.serialize = function (parent) {
  41580. return _super.prototype._serialize.call(this, {
  41581. name: "SetStateAction",
  41582. properties: [
  41583. BABYLON.Action._GetTargetProperty(this._target),
  41584. { name: "value", value: this.value }
  41585. ]
  41586. }, parent);
  41587. };
  41588. return SetStateAction;
  41589. }(BABYLON.Action));
  41590. BABYLON.SetStateAction = SetStateAction;
  41591. var SetValueAction = (function (_super) {
  41592. __extends(SetValueAction, _super);
  41593. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  41594. var _this = _super.call(this, triggerOptions, condition) || this;
  41595. _this.propertyPath = propertyPath;
  41596. _this.value = value;
  41597. _this._target = _this._effectiveTarget = target;
  41598. return _this;
  41599. }
  41600. SetValueAction.prototype._prepare = function () {
  41601. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  41602. this._property = this._getProperty(this.propertyPath);
  41603. };
  41604. SetValueAction.prototype.execute = function () {
  41605. this._effectiveTarget[this._property] = this.value;
  41606. if (this._target.markAsDirty) {
  41607. this._target.markAsDirty(this._property);
  41608. }
  41609. };
  41610. SetValueAction.prototype.serialize = function (parent) {
  41611. return _super.prototype._serialize.call(this, {
  41612. name: "SetValueAction",
  41613. properties: [
  41614. BABYLON.Action._GetTargetProperty(this._target),
  41615. { name: "propertyPath", value: this.propertyPath },
  41616. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  41617. ]
  41618. }, parent);
  41619. };
  41620. return SetValueAction;
  41621. }(BABYLON.Action));
  41622. BABYLON.SetValueAction = SetValueAction;
  41623. var IncrementValueAction = (function (_super) {
  41624. __extends(IncrementValueAction, _super);
  41625. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  41626. var _this = _super.call(this, triggerOptions, condition) || this;
  41627. _this.propertyPath = propertyPath;
  41628. _this.value = value;
  41629. _this._target = _this._effectiveTarget = target;
  41630. return _this;
  41631. }
  41632. IncrementValueAction.prototype._prepare = function () {
  41633. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  41634. this._property = this._getProperty(this.propertyPath);
  41635. if (typeof this._effectiveTarget[this._property] !== "number") {
  41636. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  41637. }
  41638. };
  41639. IncrementValueAction.prototype.execute = function () {
  41640. this._effectiveTarget[this._property] += this.value;
  41641. if (this._target.markAsDirty) {
  41642. this._target.markAsDirty(this._property);
  41643. }
  41644. };
  41645. IncrementValueAction.prototype.serialize = function (parent) {
  41646. return _super.prototype._serialize.call(this, {
  41647. name: "IncrementValueAction",
  41648. properties: [
  41649. BABYLON.Action._GetTargetProperty(this._target),
  41650. { name: "propertyPath", value: this.propertyPath },
  41651. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  41652. ]
  41653. }, parent);
  41654. };
  41655. return IncrementValueAction;
  41656. }(BABYLON.Action));
  41657. BABYLON.IncrementValueAction = IncrementValueAction;
  41658. var PlayAnimationAction = (function (_super) {
  41659. __extends(PlayAnimationAction, _super);
  41660. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  41661. var _this = _super.call(this, triggerOptions, condition) || this;
  41662. _this.from = from;
  41663. _this.to = to;
  41664. _this.loop = loop;
  41665. _this._target = target;
  41666. return _this;
  41667. }
  41668. PlayAnimationAction.prototype._prepare = function () {
  41669. };
  41670. PlayAnimationAction.prototype.execute = function () {
  41671. var scene = this._actionManager.getScene();
  41672. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  41673. };
  41674. PlayAnimationAction.prototype.serialize = function (parent) {
  41675. return _super.prototype._serialize.call(this, {
  41676. name: "PlayAnimationAction",
  41677. properties: [
  41678. BABYLON.Action._GetTargetProperty(this._target),
  41679. { name: "from", value: String(this.from) },
  41680. { name: "to", value: String(this.to) },
  41681. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  41682. ]
  41683. }, parent);
  41684. };
  41685. return PlayAnimationAction;
  41686. }(BABYLON.Action));
  41687. BABYLON.PlayAnimationAction = PlayAnimationAction;
  41688. var StopAnimationAction = (function (_super) {
  41689. __extends(StopAnimationAction, _super);
  41690. function StopAnimationAction(triggerOptions, target, condition) {
  41691. var _this = _super.call(this, triggerOptions, condition) || this;
  41692. _this._target = target;
  41693. return _this;
  41694. }
  41695. StopAnimationAction.prototype._prepare = function () {
  41696. };
  41697. StopAnimationAction.prototype.execute = function () {
  41698. var scene = this._actionManager.getScene();
  41699. scene.stopAnimation(this._target);
  41700. };
  41701. StopAnimationAction.prototype.serialize = function (parent) {
  41702. return _super.prototype._serialize.call(this, {
  41703. name: "StopAnimationAction",
  41704. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  41705. }, parent);
  41706. };
  41707. return StopAnimationAction;
  41708. }(BABYLON.Action));
  41709. BABYLON.StopAnimationAction = StopAnimationAction;
  41710. var DoNothingAction = (function (_super) {
  41711. __extends(DoNothingAction, _super);
  41712. function DoNothingAction(triggerOptions, condition) {
  41713. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  41714. return _super.call(this, triggerOptions, condition) || this;
  41715. }
  41716. DoNothingAction.prototype.execute = function () {
  41717. };
  41718. DoNothingAction.prototype.serialize = function (parent) {
  41719. return _super.prototype._serialize.call(this, {
  41720. name: "DoNothingAction",
  41721. properties: []
  41722. }, parent);
  41723. };
  41724. return DoNothingAction;
  41725. }(BABYLON.Action));
  41726. BABYLON.DoNothingAction = DoNothingAction;
  41727. var CombineAction = (function (_super) {
  41728. __extends(CombineAction, _super);
  41729. function CombineAction(triggerOptions, children, condition) {
  41730. var _this = _super.call(this, triggerOptions, condition) || this;
  41731. _this.children = children;
  41732. return _this;
  41733. }
  41734. CombineAction.prototype._prepare = function () {
  41735. for (var index = 0; index < this.children.length; index++) {
  41736. this.children[index]._actionManager = this._actionManager;
  41737. this.children[index]._prepare();
  41738. }
  41739. };
  41740. CombineAction.prototype.execute = function (evt) {
  41741. for (var index = 0; index < this.children.length; index++) {
  41742. this.children[index].execute(evt);
  41743. }
  41744. };
  41745. CombineAction.prototype.serialize = function (parent) {
  41746. var serializationObject = _super.prototype._serialize.call(this, {
  41747. name: "CombineAction",
  41748. properties: [],
  41749. combine: []
  41750. }, parent);
  41751. for (var i = 0; i < this.children.length; i++) {
  41752. serializationObject.combine.push(this.children[i].serialize(null));
  41753. }
  41754. return serializationObject;
  41755. };
  41756. return CombineAction;
  41757. }(BABYLON.Action));
  41758. BABYLON.CombineAction = CombineAction;
  41759. var ExecuteCodeAction = (function (_super) {
  41760. __extends(ExecuteCodeAction, _super);
  41761. function ExecuteCodeAction(triggerOptions, func, condition) {
  41762. var _this = _super.call(this, triggerOptions, condition) || this;
  41763. _this.func = func;
  41764. return _this;
  41765. }
  41766. ExecuteCodeAction.prototype.execute = function (evt) {
  41767. this.func(evt);
  41768. };
  41769. return ExecuteCodeAction;
  41770. }(BABYLON.Action));
  41771. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  41772. var SetParentAction = (function (_super) {
  41773. __extends(SetParentAction, _super);
  41774. function SetParentAction(triggerOptions, target, parent, condition) {
  41775. var _this = _super.call(this, triggerOptions, condition) || this;
  41776. _this._target = target;
  41777. _this._parent = parent;
  41778. return _this;
  41779. }
  41780. SetParentAction.prototype._prepare = function () {
  41781. };
  41782. SetParentAction.prototype.execute = function () {
  41783. if (this._target.parent === this._parent) {
  41784. return;
  41785. }
  41786. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  41787. invertParentWorldMatrix.invert();
  41788. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  41789. this._target.parent = this._parent;
  41790. };
  41791. SetParentAction.prototype.serialize = function (parent) {
  41792. return _super.prototype._serialize.call(this, {
  41793. name: "SetParentAction",
  41794. properties: [
  41795. BABYLON.Action._GetTargetProperty(this._target),
  41796. BABYLON.Action._GetTargetProperty(this._parent),
  41797. ]
  41798. }, parent);
  41799. };
  41800. return SetParentAction;
  41801. }(BABYLON.Action));
  41802. BABYLON.SetParentAction = SetParentAction;
  41803. var PlaySoundAction = (function (_super) {
  41804. __extends(PlaySoundAction, _super);
  41805. function PlaySoundAction(triggerOptions, sound, condition) {
  41806. var _this = _super.call(this, triggerOptions, condition) || this;
  41807. _this._sound = sound;
  41808. return _this;
  41809. }
  41810. PlaySoundAction.prototype._prepare = function () {
  41811. };
  41812. PlaySoundAction.prototype.execute = function () {
  41813. if (this._sound !== undefined)
  41814. this._sound.play();
  41815. };
  41816. PlaySoundAction.prototype.serialize = function (parent) {
  41817. return _super.prototype._serialize.call(this, {
  41818. name: "PlaySoundAction",
  41819. properties: [{ name: "sound", value: this._sound.name }]
  41820. }, parent);
  41821. };
  41822. return PlaySoundAction;
  41823. }(BABYLON.Action));
  41824. BABYLON.PlaySoundAction = PlaySoundAction;
  41825. var StopSoundAction = (function (_super) {
  41826. __extends(StopSoundAction, _super);
  41827. function StopSoundAction(triggerOptions, sound, condition) {
  41828. var _this = _super.call(this, triggerOptions, condition) || this;
  41829. _this._sound = sound;
  41830. return _this;
  41831. }
  41832. StopSoundAction.prototype._prepare = function () {
  41833. };
  41834. StopSoundAction.prototype.execute = function () {
  41835. if (this._sound !== undefined)
  41836. this._sound.stop();
  41837. };
  41838. StopSoundAction.prototype.serialize = function (parent) {
  41839. return _super.prototype._serialize.call(this, {
  41840. name: "StopSoundAction",
  41841. properties: [{ name: "sound", value: this._sound.name }]
  41842. }, parent);
  41843. };
  41844. return StopSoundAction;
  41845. }(BABYLON.Action));
  41846. BABYLON.StopSoundAction = StopSoundAction;
  41847. })(BABYLON || (BABYLON = {}));
  41848. //# sourceMappingURL=babylon.directActions.js.map
  41849. var BABYLON;
  41850. (function (BABYLON) {
  41851. var Geometry = (function () {
  41852. function Geometry(id, scene, vertexData, updatable, mesh) {
  41853. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  41854. this._totalVertices = 0;
  41855. this._isDisposed = false;
  41856. this.id = id;
  41857. this._engine = scene.getEngine();
  41858. this._meshes = [];
  41859. this._scene = scene;
  41860. //Init vertex buffer cache
  41861. this._vertexBuffers = {};
  41862. this._indices = [];
  41863. // vertexData
  41864. if (vertexData) {
  41865. this.setAllVerticesData(vertexData, updatable);
  41866. }
  41867. else {
  41868. this._totalVertices = 0;
  41869. this._indices = [];
  41870. }
  41871. if (this._engine.getCaps().vertexArrayObject) {
  41872. this._vertexArrayObjects = {};
  41873. }
  41874. // applyToMesh
  41875. if (mesh) {
  41876. if (mesh instanceof BABYLON.LinesMesh) {
  41877. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  41878. this.updateExtend();
  41879. }
  41880. this.applyToMesh(mesh);
  41881. mesh.computeWorldMatrix(true);
  41882. }
  41883. }
  41884. Object.defineProperty(Geometry.prototype, "boundingBias", {
  41885. /**
  41886. * 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
  41887. * @returns The Bias Vector
  41888. */
  41889. get: function () {
  41890. return this._boundingBias;
  41891. },
  41892. set: function (value) {
  41893. if (this._boundingBias && this._boundingBias.equals(value)) {
  41894. return;
  41895. }
  41896. this._boundingBias = value.clone();
  41897. this.updateBoundingInfo(true, null);
  41898. },
  41899. enumerable: true,
  41900. configurable: true
  41901. });
  41902. Object.defineProperty(Geometry.prototype, "extend", {
  41903. get: function () {
  41904. return this._extend;
  41905. },
  41906. enumerable: true,
  41907. configurable: true
  41908. });
  41909. Geometry.prototype.getScene = function () {
  41910. return this._scene;
  41911. };
  41912. Geometry.prototype.getEngine = function () {
  41913. return this._engine;
  41914. };
  41915. Geometry.prototype.isReady = function () {
  41916. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  41917. };
  41918. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  41919. get: function () {
  41920. for (var index = 0; index < this._meshes.length; index++) {
  41921. if (!this._meshes[index].doNotSerialize) {
  41922. return false;
  41923. }
  41924. }
  41925. return true;
  41926. },
  41927. enumerable: true,
  41928. configurable: true
  41929. });
  41930. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  41931. vertexData.applyToGeometry(this, updatable);
  41932. this.notifyUpdate();
  41933. };
  41934. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  41935. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  41936. this.setVerticesBuffer(buffer);
  41937. };
  41938. Geometry.prototype.setVerticesBuffer = function (buffer) {
  41939. var kind = buffer.getKind();
  41940. if (this._vertexBuffers[kind]) {
  41941. this._vertexBuffers[kind].dispose();
  41942. }
  41943. this._vertexBuffers[kind] = buffer;
  41944. if (kind === BABYLON.VertexBuffer.PositionKind) {
  41945. var data = buffer.getData();
  41946. var stride = buffer.getStrideSize();
  41947. this._totalVertices = data.length / stride;
  41948. this.updateExtend(data, stride);
  41949. var meshes = this._meshes;
  41950. var numOfMeshes = meshes.length;
  41951. for (var index = 0; index < numOfMeshes; index++) {
  41952. var mesh = meshes[index];
  41953. mesh._resetPointsArrayCache();
  41954. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41955. mesh._createGlobalSubMesh();
  41956. mesh.computeWorldMatrix(true);
  41957. }
  41958. }
  41959. this.notifyUpdate(kind);
  41960. if (this._vertexArrayObjects) {
  41961. this._disposeVertexArrayObjects();
  41962. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  41963. }
  41964. };
  41965. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  41966. var vertexBuffer = this.getVertexBuffer(kind);
  41967. if (!vertexBuffer) {
  41968. return;
  41969. }
  41970. vertexBuffer.updateDirectly(data, offset);
  41971. this.notifyUpdate(kind);
  41972. };
  41973. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  41974. var vertexBuffer = this.getVertexBuffer(kind);
  41975. if (!vertexBuffer) {
  41976. return;
  41977. }
  41978. vertexBuffer.update(data);
  41979. if (kind === BABYLON.VertexBuffer.PositionKind) {
  41980. var stride = vertexBuffer.getStrideSize();
  41981. this._totalVertices = data.length / stride;
  41982. this.updateBoundingInfo(updateExtends, data);
  41983. }
  41984. this.notifyUpdate(kind);
  41985. };
  41986. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  41987. if (updateExtends) {
  41988. this.updateExtend(data);
  41989. }
  41990. var meshes = this._meshes;
  41991. var numOfMeshes = meshes.length;
  41992. for (var index = 0; index < numOfMeshes; index++) {
  41993. var mesh = meshes[index];
  41994. mesh._resetPointsArrayCache();
  41995. if (updateExtends) {
  41996. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41997. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  41998. var subMesh = mesh.subMeshes[subIndex];
  41999. subMesh.refreshBoundingInfo();
  42000. }
  42001. }
  42002. }
  42003. };
  42004. Geometry.prototype._bind = function (effect, indexToBind) {
  42005. if (indexToBind === void 0) { indexToBind = undefined; }
  42006. if (indexToBind === undefined) {
  42007. indexToBind = this._indexBuffer;
  42008. }
  42009. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  42010. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  42011. return;
  42012. }
  42013. // Using VAO
  42014. if (!this._vertexArrayObjects[effect.key]) {
  42015. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  42016. }
  42017. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  42018. };
  42019. Geometry.prototype.getTotalVertices = function () {
  42020. if (!this.isReady()) {
  42021. return 0;
  42022. }
  42023. return this._totalVertices;
  42024. };
  42025. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  42026. var vertexBuffer = this.getVertexBuffer(kind);
  42027. if (!vertexBuffer) {
  42028. return null;
  42029. }
  42030. var orig = vertexBuffer.getData();
  42031. if (!copyWhenShared || this._meshes.length === 1) {
  42032. return orig;
  42033. }
  42034. else {
  42035. var len = orig.length;
  42036. var copy = [];
  42037. for (var i = 0; i < len; i++) {
  42038. copy.push(orig[i]);
  42039. }
  42040. return copy;
  42041. }
  42042. };
  42043. Geometry.prototype.getVertexBuffer = function (kind) {
  42044. if (!this.isReady()) {
  42045. return null;
  42046. }
  42047. return this._vertexBuffers[kind];
  42048. };
  42049. Geometry.prototype.getVertexBuffers = function () {
  42050. if (!this.isReady()) {
  42051. return null;
  42052. }
  42053. return this._vertexBuffers;
  42054. };
  42055. Geometry.prototype.isVerticesDataPresent = function (kind) {
  42056. if (!this._vertexBuffers) {
  42057. if (this._delayInfo) {
  42058. return this._delayInfo.indexOf(kind) !== -1;
  42059. }
  42060. return false;
  42061. }
  42062. return this._vertexBuffers[kind] !== undefined;
  42063. };
  42064. Geometry.prototype.getVerticesDataKinds = function () {
  42065. var result = [];
  42066. var kind;
  42067. if (!this._vertexBuffers && this._delayInfo) {
  42068. for (kind in this._delayInfo) {
  42069. result.push(kind);
  42070. }
  42071. }
  42072. else {
  42073. for (kind in this._vertexBuffers) {
  42074. result.push(kind);
  42075. }
  42076. }
  42077. return result;
  42078. };
  42079. Geometry.prototype.setIndices = function (indices, totalVertices) {
  42080. if (this._indexBuffer) {
  42081. this._engine._releaseBuffer(this._indexBuffer);
  42082. }
  42083. this._disposeVertexArrayObjects();
  42084. this._indices = indices;
  42085. if (this._meshes.length !== 0 && this._indices) {
  42086. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  42087. }
  42088. if (totalVertices !== undefined) {
  42089. this._totalVertices = totalVertices;
  42090. }
  42091. var meshes = this._meshes;
  42092. var numOfMeshes = meshes.length;
  42093. for (var index = 0; index < numOfMeshes; index++) {
  42094. meshes[index]._createGlobalSubMesh();
  42095. }
  42096. this.notifyUpdate();
  42097. };
  42098. Geometry.prototype.getTotalIndices = function () {
  42099. if (!this.isReady()) {
  42100. return 0;
  42101. }
  42102. return this._indices.length;
  42103. };
  42104. Geometry.prototype.getIndices = function (copyWhenShared) {
  42105. if (!this.isReady()) {
  42106. return null;
  42107. }
  42108. var orig = this._indices;
  42109. if (!copyWhenShared || this._meshes.length === 1) {
  42110. return orig;
  42111. }
  42112. else {
  42113. var len = orig.length;
  42114. var copy = [];
  42115. for (var i = 0; i < len; i++) {
  42116. copy.push(orig[i]);
  42117. }
  42118. return copy;
  42119. }
  42120. };
  42121. Geometry.prototype.getIndexBuffer = function () {
  42122. if (!this.isReady()) {
  42123. return null;
  42124. }
  42125. return this._indexBuffer;
  42126. };
  42127. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  42128. var meshes = this._meshes;
  42129. var index = meshes.indexOf(mesh);
  42130. if (index === -1) {
  42131. return;
  42132. }
  42133. meshes.splice(index, 1);
  42134. mesh._geometry = null;
  42135. if (meshes.length === 0 && shouldDispose) {
  42136. this.dispose();
  42137. }
  42138. };
  42139. Geometry.prototype.applyToMesh = function (mesh) {
  42140. if (mesh._geometry === this) {
  42141. return;
  42142. }
  42143. var previousGeometry = mesh._geometry;
  42144. if (previousGeometry) {
  42145. previousGeometry.releaseForMesh(mesh);
  42146. }
  42147. var meshes = this._meshes;
  42148. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  42149. mesh._geometry = this;
  42150. this._scene.pushGeometry(this);
  42151. meshes.push(mesh);
  42152. if (this.isReady()) {
  42153. this._applyToMesh(mesh);
  42154. }
  42155. else {
  42156. mesh._boundingInfo = this._boundingInfo;
  42157. }
  42158. };
  42159. Geometry.prototype.updateExtend = function (data, stride) {
  42160. if (data === void 0) { data = null; }
  42161. if (!data) {
  42162. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  42163. }
  42164. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  42165. };
  42166. Geometry.prototype._applyToMesh = function (mesh) {
  42167. var numOfMeshes = this._meshes.length;
  42168. // vertexBuffers
  42169. for (var kind in this._vertexBuffers) {
  42170. if (numOfMeshes === 1) {
  42171. this._vertexBuffers[kind].create();
  42172. }
  42173. var buffer = this._vertexBuffers[kind].getBuffer();
  42174. if (buffer)
  42175. buffer.references = numOfMeshes;
  42176. if (kind === BABYLON.VertexBuffer.PositionKind) {
  42177. mesh._resetPointsArrayCache();
  42178. if (!this._extend) {
  42179. this.updateExtend(this._vertexBuffers[kind].getData());
  42180. }
  42181. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  42182. mesh._createGlobalSubMesh();
  42183. //bounding info was just created again, world matrix should be applied again.
  42184. mesh._updateBoundingInfo();
  42185. }
  42186. }
  42187. // indexBuffer
  42188. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  42189. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  42190. }
  42191. if (this._indexBuffer) {
  42192. this._indexBuffer.references = numOfMeshes;
  42193. }
  42194. };
  42195. Geometry.prototype.notifyUpdate = function (kind) {
  42196. if (this.onGeometryUpdated) {
  42197. this.onGeometryUpdated(this, kind);
  42198. }
  42199. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  42200. var mesh = _a[_i];
  42201. mesh._markSubMeshesAsAttributesDirty();
  42202. }
  42203. };
  42204. Geometry.prototype.load = function (scene, onLoaded) {
  42205. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  42206. return;
  42207. }
  42208. if (this.isReady()) {
  42209. if (onLoaded) {
  42210. onLoaded();
  42211. }
  42212. return;
  42213. }
  42214. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  42215. this._queueLoad(scene, onLoaded);
  42216. };
  42217. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  42218. var _this = this;
  42219. scene._addPendingData(this);
  42220. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  42221. _this._delayLoadingFunction(JSON.parse(data), _this);
  42222. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  42223. _this._delayInfo = [];
  42224. scene._removePendingData(_this);
  42225. var meshes = _this._meshes;
  42226. var numOfMeshes = meshes.length;
  42227. for (var index = 0; index < numOfMeshes; index++) {
  42228. _this._applyToMesh(meshes[index]);
  42229. }
  42230. if (onLoaded) {
  42231. onLoaded();
  42232. }
  42233. }, function () { }, scene.database);
  42234. };
  42235. /**
  42236. * Invert the geometry to move from a right handed system to a left handed one.
  42237. */
  42238. Geometry.prototype.toLeftHanded = function () {
  42239. // Flip faces
  42240. var tIndices = this.getIndices(false);
  42241. if (tIndices != null && tIndices.length > 0) {
  42242. for (var i = 0; i < tIndices.length; i += 3) {
  42243. var tTemp = tIndices[i + 0];
  42244. tIndices[i + 0] = tIndices[i + 2];
  42245. tIndices[i + 2] = tTemp;
  42246. }
  42247. this.setIndices(tIndices);
  42248. }
  42249. // Negate position.z
  42250. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  42251. if (tPositions != null && tPositions.length > 0) {
  42252. for (var i = 0; i < tPositions.length; i += 3) {
  42253. tPositions[i + 2] = -tPositions[i + 2];
  42254. }
  42255. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  42256. }
  42257. // Negate normal.z
  42258. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  42259. if (tNormals != null && tNormals.length > 0) {
  42260. for (var i = 0; i < tNormals.length; i += 3) {
  42261. tNormals[i + 2] = -tNormals[i + 2];
  42262. }
  42263. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  42264. }
  42265. };
  42266. Geometry.prototype.isDisposed = function () {
  42267. return this._isDisposed;
  42268. };
  42269. Geometry.prototype._disposeVertexArrayObjects = function () {
  42270. if (this._vertexArrayObjects) {
  42271. for (var kind in this._vertexArrayObjects) {
  42272. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  42273. }
  42274. this._vertexArrayObjects = {};
  42275. }
  42276. };
  42277. Geometry.prototype.dispose = function () {
  42278. var meshes = this._meshes;
  42279. var numOfMeshes = meshes.length;
  42280. var index;
  42281. for (index = 0; index < numOfMeshes; index++) {
  42282. this.releaseForMesh(meshes[index]);
  42283. }
  42284. this._meshes = [];
  42285. this._disposeVertexArrayObjects();
  42286. for (var kind in this._vertexBuffers) {
  42287. this._vertexBuffers[kind].dispose();
  42288. }
  42289. this._vertexBuffers = {};
  42290. this._totalVertices = 0;
  42291. if (this._indexBuffer) {
  42292. this._engine._releaseBuffer(this._indexBuffer);
  42293. }
  42294. this._indexBuffer = null;
  42295. this._indices = [];
  42296. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  42297. this.delayLoadingFile = null;
  42298. this._delayLoadingFunction = null;
  42299. this._delayInfo = [];
  42300. this._boundingInfo = null;
  42301. this._scene.removeGeometry(this);
  42302. this._isDisposed = true;
  42303. };
  42304. Geometry.prototype.copy = function (id) {
  42305. var vertexData = new BABYLON.VertexData();
  42306. vertexData.indices = [];
  42307. var indices = this.getIndices();
  42308. for (var index = 0; index < indices.length; index++) {
  42309. vertexData.indices.push(indices[index]);
  42310. }
  42311. var updatable = false;
  42312. var stopChecking = false;
  42313. var kind;
  42314. for (kind in this._vertexBuffers) {
  42315. // using slice() to make a copy of the array and not just reference it
  42316. var data = this.getVerticesData(kind);
  42317. if (data instanceof Float32Array) {
  42318. vertexData.set(new Float32Array(data), kind);
  42319. }
  42320. else {
  42321. vertexData.set(data.slice(0), kind);
  42322. }
  42323. if (!stopChecking) {
  42324. updatable = this.getVertexBuffer(kind).isUpdatable();
  42325. stopChecking = !updatable;
  42326. }
  42327. }
  42328. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  42329. geometry.delayLoadState = this.delayLoadState;
  42330. geometry.delayLoadingFile = this.delayLoadingFile;
  42331. geometry._delayLoadingFunction = this._delayLoadingFunction;
  42332. for (kind in this._delayInfo) {
  42333. geometry._delayInfo = geometry._delayInfo || [];
  42334. geometry._delayInfo.push(kind);
  42335. }
  42336. // Bounding info
  42337. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  42338. return geometry;
  42339. };
  42340. Geometry.prototype.serialize = function () {
  42341. var serializationObject = {};
  42342. serializationObject.id = this.id;
  42343. if (BABYLON.Tags.HasTags(this)) {
  42344. serializationObject.tags = BABYLON.Tags.GetTags(this);
  42345. }
  42346. return serializationObject;
  42347. };
  42348. Geometry.prototype.serializeVerticeData = function () {
  42349. var serializationObject = this.serialize();
  42350. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  42351. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42352. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  42353. serializationObject.positions._updatable = true;
  42354. }
  42355. }
  42356. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  42357. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42358. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  42359. serializationObject.normals._updatable = true;
  42360. }
  42361. }
  42362. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42363. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42364. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  42365. serializationObject.uvs._updatable = true;
  42366. }
  42367. }
  42368. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  42369. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  42370. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  42371. serializationObject.uv2s._updatable = true;
  42372. }
  42373. }
  42374. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  42375. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  42376. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  42377. serializationObject.uv3s._updatable = true;
  42378. }
  42379. }
  42380. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  42381. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  42382. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  42383. serializationObject.uv4s._updatable = true;
  42384. }
  42385. }
  42386. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  42387. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  42388. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  42389. serializationObject.uv5s._updatable = true;
  42390. }
  42391. }
  42392. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  42393. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  42394. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  42395. serializationObject.uv6s._updatable = true;
  42396. }
  42397. }
  42398. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  42399. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42400. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  42401. serializationObject.colors._updatable = true;
  42402. }
  42403. }
  42404. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  42405. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  42406. serializationObject.matricesIndices._isExpanded = true;
  42407. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  42408. serializationObject.matricesIndices._updatable = true;
  42409. }
  42410. }
  42411. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  42412. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  42413. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  42414. serializationObject.matricesWeights._updatable = true;
  42415. }
  42416. }
  42417. serializationObject.indices = this.getIndices();
  42418. return serializationObject;
  42419. };
  42420. // Statics
  42421. Geometry.ExtractFromMesh = function (mesh, id) {
  42422. var geometry = mesh._geometry;
  42423. if (!geometry) {
  42424. return null;
  42425. }
  42426. return geometry.copy(id);
  42427. };
  42428. /**
  42429. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  42430. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  42431. * Be aware Math.random() could cause collisions, but:
  42432. * "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"
  42433. */
  42434. Geometry.RandomId = function () {
  42435. return BABYLON.Tools.RandomId();
  42436. };
  42437. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  42438. var scene = mesh.getScene();
  42439. // Geometry
  42440. var geometryId = parsedGeometry.geometryId;
  42441. if (geometryId) {
  42442. var geometry = scene.getGeometryByID(geometryId);
  42443. if (geometry) {
  42444. geometry.applyToMesh(mesh);
  42445. }
  42446. }
  42447. else if (parsedGeometry instanceof ArrayBuffer) {
  42448. var binaryInfo = mesh._binaryInfo;
  42449. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  42450. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  42451. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  42452. }
  42453. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  42454. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  42455. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  42456. }
  42457. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  42458. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  42459. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  42460. }
  42461. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  42462. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  42463. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  42464. }
  42465. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  42466. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  42467. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  42468. }
  42469. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  42470. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  42471. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  42472. }
  42473. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  42474. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  42475. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  42476. }
  42477. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  42478. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  42479. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  42480. }
  42481. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  42482. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  42483. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  42484. }
  42485. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  42486. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  42487. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  42488. }
  42489. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  42490. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  42491. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  42492. }
  42493. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  42494. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  42495. mesh.setIndices(indicesData);
  42496. }
  42497. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  42498. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  42499. mesh.subMeshes = [];
  42500. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  42501. var materialIndex = subMeshesData[(i * 5) + 0];
  42502. var verticesStart = subMeshesData[(i * 5) + 1];
  42503. var verticesCount = subMeshesData[(i * 5) + 2];
  42504. var indexStart = subMeshesData[(i * 5) + 3];
  42505. var indexCount = subMeshesData[(i * 5) + 4];
  42506. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  42507. }
  42508. }
  42509. }
  42510. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  42511. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  42512. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  42513. if (parsedGeometry.uvs) {
  42514. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  42515. }
  42516. if (parsedGeometry.uvs2) {
  42517. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  42518. }
  42519. if (parsedGeometry.uvs3) {
  42520. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  42521. }
  42522. if (parsedGeometry.uvs4) {
  42523. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  42524. }
  42525. if (parsedGeometry.uvs5) {
  42526. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  42527. }
  42528. if (parsedGeometry.uvs6) {
  42529. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  42530. }
  42531. if (parsedGeometry.colors) {
  42532. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  42533. }
  42534. if (parsedGeometry.matricesIndices) {
  42535. if (!parsedGeometry.matricesIndices._isExpanded) {
  42536. var floatIndices = [];
  42537. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  42538. var matricesIndex = parsedGeometry.matricesIndices[i];
  42539. floatIndices.push(matricesIndex & 0x000000FF);
  42540. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  42541. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  42542. floatIndices.push(matricesIndex >> 24);
  42543. }
  42544. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  42545. }
  42546. else {
  42547. delete parsedGeometry.matricesIndices._isExpanded;
  42548. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  42549. }
  42550. }
  42551. if (parsedGeometry.matricesIndicesExtra) {
  42552. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  42553. var floatIndices = [];
  42554. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  42555. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  42556. floatIndices.push(matricesIndex & 0x000000FF);
  42557. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  42558. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  42559. floatIndices.push(matricesIndex >> 24);
  42560. }
  42561. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  42562. }
  42563. else {
  42564. delete parsedGeometry.matricesIndices._isExpanded;
  42565. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  42566. }
  42567. }
  42568. if (parsedGeometry.matricesWeights) {
  42569. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  42570. }
  42571. if (parsedGeometry.matricesWeightsExtra) {
  42572. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  42573. }
  42574. mesh.setIndices(parsedGeometry.indices);
  42575. }
  42576. // SubMeshes
  42577. if (parsedGeometry.subMeshes) {
  42578. mesh.subMeshes = [];
  42579. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  42580. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  42581. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  42582. }
  42583. }
  42584. // Flat shading
  42585. if (mesh._shouldGenerateFlatShading) {
  42586. mesh.convertToFlatShadedMesh();
  42587. delete mesh._shouldGenerateFlatShading;
  42588. }
  42589. // Update
  42590. mesh.computeWorldMatrix(true);
  42591. // Octree
  42592. if (scene['_selectionOctree']) {
  42593. scene['_selectionOctree'].addMesh(mesh);
  42594. }
  42595. };
  42596. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  42597. if (scene.getGeometryByID(parsedVertexData.id)) {
  42598. return null; // null since geometry could be something else than a box...
  42599. }
  42600. var geometry = new Geometry(parsedVertexData.id, scene);
  42601. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  42602. if (parsedVertexData.delayLoadingFile) {
  42603. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  42604. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  42605. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  42606. geometry._delayInfo = [];
  42607. if (parsedVertexData.hasUVs) {
  42608. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  42609. }
  42610. if (parsedVertexData.hasUVs2) {
  42611. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  42612. }
  42613. if (parsedVertexData.hasUVs3) {
  42614. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  42615. }
  42616. if (parsedVertexData.hasUVs4) {
  42617. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  42618. }
  42619. if (parsedVertexData.hasUVs5) {
  42620. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  42621. }
  42622. if (parsedVertexData.hasUVs6) {
  42623. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  42624. }
  42625. if (parsedVertexData.hasColors) {
  42626. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  42627. }
  42628. if (parsedVertexData.hasMatricesIndices) {
  42629. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42630. }
  42631. if (parsedVertexData.hasMatricesWeights) {
  42632. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42633. }
  42634. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  42635. }
  42636. else {
  42637. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  42638. }
  42639. scene.pushGeometry(geometry, true);
  42640. return geometry;
  42641. };
  42642. return Geometry;
  42643. }());
  42644. BABYLON.Geometry = Geometry;
  42645. /////// Primitives //////////////////////////////////////////////
  42646. (function (Geometry) {
  42647. var Primitives;
  42648. (function (Primitives) {
  42649. /// Abstract class
  42650. var _Primitive = (function (_super) {
  42651. __extends(_Primitive, _super);
  42652. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  42653. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  42654. _this._canBeRegenerated = _canBeRegenerated;
  42655. _this._beingRegenerated = true;
  42656. _this.regenerate();
  42657. _this._beingRegenerated = false;
  42658. return _this;
  42659. }
  42660. _Primitive.prototype.canBeRegenerated = function () {
  42661. return this._canBeRegenerated;
  42662. };
  42663. _Primitive.prototype.regenerate = function () {
  42664. if (!this._canBeRegenerated) {
  42665. return;
  42666. }
  42667. this._beingRegenerated = true;
  42668. this.setAllVerticesData(this._regenerateVertexData(), false);
  42669. this._beingRegenerated = false;
  42670. };
  42671. _Primitive.prototype.asNewGeometry = function (id) {
  42672. return _super.prototype.copy.call(this, id);
  42673. };
  42674. // overrides
  42675. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  42676. if (!this._beingRegenerated) {
  42677. return;
  42678. }
  42679. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  42680. };
  42681. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  42682. if (!this._beingRegenerated) {
  42683. return;
  42684. }
  42685. _super.prototype.setVerticesData.call(this, kind, data, false);
  42686. };
  42687. // to override
  42688. // protected
  42689. _Primitive.prototype._regenerateVertexData = function () {
  42690. throw new Error("Abstract method");
  42691. };
  42692. _Primitive.prototype.copy = function (id) {
  42693. throw new Error("Must be overriden in sub-classes.");
  42694. };
  42695. _Primitive.prototype.serialize = function () {
  42696. var serializationObject = _super.prototype.serialize.call(this);
  42697. serializationObject.canBeRegenerated = this.canBeRegenerated();
  42698. return serializationObject;
  42699. };
  42700. return _Primitive;
  42701. }(Geometry));
  42702. Primitives._Primitive = _Primitive;
  42703. var Ribbon = (function (_super) {
  42704. __extends(Ribbon, _super);
  42705. // Members
  42706. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  42707. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42708. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42709. _this.pathArray = pathArray;
  42710. _this.closeArray = closeArray;
  42711. _this.closePath = closePath;
  42712. _this.offset = offset;
  42713. _this.side = side;
  42714. return _this;
  42715. }
  42716. Ribbon.prototype._regenerateVertexData = function () {
  42717. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  42718. };
  42719. Ribbon.prototype.copy = function (id) {
  42720. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  42721. };
  42722. return Ribbon;
  42723. }(_Primitive));
  42724. Primitives.Ribbon = Ribbon;
  42725. var Box = (function (_super) {
  42726. __extends(Box, _super);
  42727. // Members
  42728. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  42729. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42730. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42731. _this.size = size;
  42732. _this.side = side;
  42733. return _this;
  42734. }
  42735. Box.prototype._regenerateVertexData = function () {
  42736. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  42737. };
  42738. Box.prototype.copy = function (id) {
  42739. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  42740. };
  42741. Box.prototype.serialize = function () {
  42742. var serializationObject = _super.prototype.serialize.call(this);
  42743. serializationObject.size = this.size;
  42744. return serializationObject;
  42745. };
  42746. Box.Parse = function (parsedBox, scene) {
  42747. if (scene.getGeometryByID(parsedBox.id)) {
  42748. return null; // null since geometry could be something else than a box...
  42749. }
  42750. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  42751. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  42752. scene.pushGeometry(box, true);
  42753. return box;
  42754. };
  42755. return Box;
  42756. }(_Primitive));
  42757. Primitives.Box = Box;
  42758. var Sphere = (function (_super) {
  42759. __extends(Sphere, _super);
  42760. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  42761. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42762. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42763. _this.segments = segments;
  42764. _this.diameter = diameter;
  42765. _this.side = side;
  42766. return _this;
  42767. }
  42768. Sphere.prototype._regenerateVertexData = function () {
  42769. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  42770. };
  42771. Sphere.prototype.copy = function (id) {
  42772. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  42773. };
  42774. Sphere.prototype.serialize = function () {
  42775. var serializationObject = _super.prototype.serialize.call(this);
  42776. serializationObject.segments = this.segments;
  42777. serializationObject.diameter = this.diameter;
  42778. return serializationObject;
  42779. };
  42780. Sphere.Parse = function (parsedSphere, scene) {
  42781. if (scene.getGeometryByID(parsedSphere.id)) {
  42782. return null; // null since geometry could be something else than a sphere...
  42783. }
  42784. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  42785. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  42786. scene.pushGeometry(sphere, true);
  42787. return sphere;
  42788. };
  42789. return Sphere;
  42790. }(_Primitive));
  42791. Primitives.Sphere = Sphere;
  42792. var Disc = (function (_super) {
  42793. __extends(Disc, _super);
  42794. // Members
  42795. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  42796. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42797. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42798. _this.radius = radius;
  42799. _this.tessellation = tessellation;
  42800. _this.side = side;
  42801. return _this;
  42802. }
  42803. Disc.prototype._regenerateVertexData = function () {
  42804. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  42805. };
  42806. Disc.prototype.copy = function (id) {
  42807. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  42808. };
  42809. return Disc;
  42810. }(_Primitive));
  42811. Primitives.Disc = Disc;
  42812. var Cylinder = (function (_super) {
  42813. __extends(Cylinder, _super);
  42814. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  42815. if (subdivisions === void 0) { subdivisions = 1; }
  42816. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42817. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42818. _this.height = height;
  42819. _this.diameterTop = diameterTop;
  42820. _this.diameterBottom = diameterBottom;
  42821. _this.tessellation = tessellation;
  42822. _this.subdivisions = subdivisions;
  42823. _this.side = side;
  42824. return _this;
  42825. }
  42826. Cylinder.prototype._regenerateVertexData = function () {
  42827. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  42828. };
  42829. Cylinder.prototype.copy = function (id) {
  42830. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  42831. };
  42832. Cylinder.prototype.serialize = function () {
  42833. var serializationObject = _super.prototype.serialize.call(this);
  42834. serializationObject.height = this.height;
  42835. serializationObject.diameterTop = this.diameterTop;
  42836. serializationObject.diameterBottom = this.diameterBottom;
  42837. serializationObject.tessellation = this.tessellation;
  42838. return serializationObject;
  42839. };
  42840. Cylinder.Parse = function (parsedCylinder, scene) {
  42841. if (scene.getGeometryByID(parsedCylinder.id)) {
  42842. return null; // null since geometry could be something else than a cylinder...
  42843. }
  42844. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  42845. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  42846. scene.pushGeometry(cylinder, true);
  42847. return cylinder;
  42848. };
  42849. return Cylinder;
  42850. }(_Primitive));
  42851. Primitives.Cylinder = Cylinder;
  42852. var Torus = (function (_super) {
  42853. __extends(Torus, _super);
  42854. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  42855. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42856. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42857. _this.diameter = diameter;
  42858. _this.thickness = thickness;
  42859. _this.tessellation = tessellation;
  42860. _this.side = side;
  42861. return _this;
  42862. }
  42863. Torus.prototype._regenerateVertexData = function () {
  42864. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  42865. };
  42866. Torus.prototype.copy = function (id) {
  42867. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  42868. };
  42869. Torus.prototype.serialize = function () {
  42870. var serializationObject = _super.prototype.serialize.call(this);
  42871. serializationObject.diameter = this.diameter;
  42872. serializationObject.thickness = this.thickness;
  42873. serializationObject.tessellation = this.tessellation;
  42874. return serializationObject;
  42875. };
  42876. Torus.Parse = function (parsedTorus, scene) {
  42877. if (scene.getGeometryByID(parsedTorus.id)) {
  42878. return null; // null since geometry could be something else than a torus...
  42879. }
  42880. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  42881. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  42882. scene.pushGeometry(torus, true);
  42883. return torus;
  42884. };
  42885. return Torus;
  42886. }(_Primitive));
  42887. Primitives.Torus = Torus;
  42888. var Ground = (function (_super) {
  42889. __extends(Ground, _super);
  42890. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  42891. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42892. _this.width = width;
  42893. _this.height = height;
  42894. _this.subdivisions = subdivisions;
  42895. return _this;
  42896. }
  42897. Ground.prototype._regenerateVertexData = function () {
  42898. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  42899. };
  42900. Ground.prototype.copy = function (id) {
  42901. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  42902. };
  42903. Ground.prototype.serialize = function () {
  42904. var serializationObject = _super.prototype.serialize.call(this);
  42905. serializationObject.width = this.width;
  42906. serializationObject.height = this.height;
  42907. serializationObject.subdivisions = this.subdivisions;
  42908. return serializationObject;
  42909. };
  42910. Ground.Parse = function (parsedGround, scene) {
  42911. if (scene.getGeometryByID(parsedGround.id)) {
  42912. return null; // null since geometry could be something else than a ground...
  42913. }
  42914. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  42915. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  42916. scene.pushGeometry(ground, true);
  42917. return ground;
  42918. };
  42919. return Ground;
  42920. }(_Primitive));
  42921. Primitives.Ground = Ground;
  42922. var TiledGround = (function (_super) {
  42923. __extends(TiledGround, _super);
  42924. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  42925. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42926. _this.xmin = xmin;
  42927. _this.zmin = zmin;
  42928. _this.xmax = xmax;
  42929. _this.zmax = zmax;
  42930. _this.subdivisions = subdivisions;
  42931. _this.precision = precision;
  42932. return _this;
  42933. }
  42934. TiledGround.prototype._regenerateVertexData = function () {
  42935. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  42936. };
  42937. TiledGround.prototype.copy = function (id) {
  42938. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  42939. };
  42940. return TiledGround;
  42941. }(_Primitive));
  42942. Primitives.TiledGround = TiledGround;
  42943. var Plane = (function (_super) {
  42944. __extends(Plane, _super);
  42945. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  42946. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42947. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42948. _this.size = size;
  42949. _this.side = side;
  42950. return _this;
  42951. }
  42952. Plane.prototype._regenerateVertexData = function () {
  42953. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  42954. };
  42955. Plane.prototype.copy = function (id) {
  42956. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  42957. };
  42958. Plane.prototype.serialize = function () {
  42959. var serializationObject = _super.prototype.serialize.call(this);
  42960. serializationObject.size = this.size;
  42961. return serializationObject;
  42962. };
  42963. Plane.Parse = function (parsedPlane, scene) {
  42964. if (scene.getGeometryByID(parsedPlane.id)) {
  42965. return null; // null since geometry could be something else than a ground...
  42966. }
  42967. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  42968. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  42969. scene.pushGeometry(plane, true);
  42970. return plane;
  42971. };
  42972. return Plane;
  42973. }(_Primitive));
  42974. Primitives.Plane = Plane;
  42975. var TorusKnot = (function (_super) {
  42976. __extends(TorusKnot, _super);
  42977. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  42978. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42979. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42980. _this.radius = radius;
  42981. _this.tube = tube;
  42982. _this.radialSegments = radialSegments;
  42983. _this.tubularSegments = tubularSegments;
  42984. _this.p = p;
  42985. _this.q = q;
  42986. _this.side = side;
  42987. return _this;
  42988. }
  42989. TorusKnot.prototype._regenerateVertexData = function () {
  42990. 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 });
  42991. };
  42992. TorusKnot.prototype.copy = function (id) {
  42993. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  42994. };
  42995. TorusKnot.prototype.serialize = function () {
  42996. var serializationObject = _super.prototype.serialize.call(this);
  42997. serializationObject.radius = this.radius;
  42998. serializationObject.tube = this.tube;
  42999. serializationObject.radialSegments = this.radialSegments;
  43000. serializationObject.tubularSegments = this.tubularSegments;
  43001. serializationObject.p = this.p;
  43002. serializationObject.q = this.q;
  43003. return serializationObject;
  43004. };
  43005. ;
  43006. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  43007. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  43008. return null; // null since geometry could be something else than a ground...
  43009. }
  43010. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  43011. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  43012. scene.pushGeometry(torusKnot, true);
  43013. return torusKnot;
  43014. };
  43015. return TorusKnot;
  43016. }(_Primitive));
  43017. Primitives.TorusKnot = TorusKnot;
  43018. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  43019. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  43020. })(BABYLON || (BABYLON = {}));
  43021. //# sourceMappingURL=babylon.geometry.js.map
  43022. /// <reference path="babylon.mesh.ts" />
  43023. var BABYLON;
  43024. (function (BABYLON) {
  43025. var GroundMesh = (function (_super) {
  43026. __extends(GroundMesh, _super);
  43027. function GroundMesh(name, scene) {
  43028. var _this = _super.call(this, name, scene) || this;
  43029. _this.generateOctree = false;
  43030. _this._worldInverse = new BABYLON.Matrix();
  43031. return _this;
  43032. }
  43033. GroundMesh.prototype.getClassName = function () {
  43034. return "GroundMesh";
  43035. };
  43036. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  43037. get: function () {
  43038. return Math.min(this._subdivisionsX, this._subdivisionsY);
  43039. },
  43040. enumerable: true,
  43041. configurable: true
  43042. });
  43043. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  43044. get: function () {
  43045. return this._subdivisionsX;
  43046. },
  43047. enumerable: true,
  43048. configurable: true
  43049. });
  43050. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  43051. get: function () {
  43052. return this._subdivisionsY;
  43053. },
  43054. enumerable: true,
  43055. configurable: true
  43056. });
  43057. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  43058. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  43059. this._subdivisionsX = chunksCount;
  43060. this._subdivisionsY = chunksCount;
  43061. this.subdivide(chunksCount);
  43062. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  43063. };
  43064. /**
  43065. * Returns a height (y) value in the Worl system :
  43066. * the ground altitude at the coordinates (x, z) expressed in the World system.
  43067. * Returns the ground y position if (x, z) are outside the ground surface.
  43068. */
  43069. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  43070. var world = this.getWorldMatrix();
  43071. var invMat = BABYLON.Tmp.Matrix[5];
  43072. world.invertToRef(invMat);
  43073. var tmpVect = BABYLON.Tmp.Vector3[8];
  43074. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  43075. x = tmpVect.x;
  43076. z = tmpVect.z;
  43077. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43078. return this.position.y;
  43079. }
  43080. if (!this._heightQuads || this._heightQuads.length == 0) {
  43081. this._initHeightQuads();
  43082. this._computeHeightQuads();
  43083. }
  43084. var facet = this._getFacetAt(x, z);
  43085. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  43086. // return y in the World system
  43087. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  43088. return tmpVect.y;
  43089. };
  43090. /**
  43091. * Returns a normalized vector (Vector3) orthogonal to the ground
  43092. * at the ground coordinates (x, z) expressed in the World system.
  43093. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  43094. */
  43095. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  43096. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  43097. this.getNormalAtCoordinatesToRef(x, z, normal);
  43098. return normal;
  43099. };
  43100. /**
  43101. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  43102. * at the ground coordinates (x, z) expressed in the World system.
  43103. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  43104. * Returns the GroundMesh.
  43105. */
  43106. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  43107. var world = this.getWorldMatrix();
  43108. var tmpMat = BABYLON.Tmp.Matrix[5];
  43109. world.invertToRef(tmpMat);
  43110. var tmpVect = BABYLON.Tmp.Vector3[8];
  43111. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  43112. x = tmpVect.x;
  43113. z = tmpVect.z;
  43114. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43115. return this;
  43116. }
  43117. if (!this._heightQuads || this._heightQuads.length == 0) {
  43118. this._initHeightQuads();
  43119. this._computeHeightQuads();
  43120. }
  43121. var facet = this._getFacetAt(x, z);
  43122. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  43123. return this;
  43124. };
  43125. /**
  43126. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  43127. * if the ground has been updated.
  43128. * This can be used in the render loop.
  43129. * Returns the GroundMesh.
  43130. */
  43131. GroundMesh.prototype.updateCoordinateHeights = function () {
  43132. if (!this._heightQuads || this._heightQuads.length == 0) {
  43133. this._initHeightQuads();
  43134. }
  43135. this._computeHeightQuads();
  43136. return this;
  43137. };
  43138. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  43139. GroundMesh.prototype._getFacetAt = function (x, z) {
  43140. // retrieve col and row from x, z coordinates in the ground local system
  43141. var subdivisionsX = this._subdivisionsX;
  43142. var subdivisionsY = this._subdivisionsY;
  43143. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  43144. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  43145. var quad = this._heightQuads[row * this._subdivisionsX + col];
  43146. var facet;
  43147. if (z < quad.slope.x * x + quad.slope.y) {
  43148. facet = quad.facet1;
  43149. }
  43150. else {
  43151. facet = quad.facet2;
  43152. }
  43153. return facet;
  43154. };
  43155. // Creates and populates the heightMap array with "facet" elements :
  43156. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  43157. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43158. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43159. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43160. // Returns the GroundMesh.
  43161. GroundMesh.prototype._initHeightQuads = function () {
  43162. var subdivisionsX = this._subdivisionsX;
  43163. var subdivisionsY = this._subdivisionsY;
  43164. this._heightQuads = new Array();
  43165. for (var row = 0; row < subdivisionsY; row++) {
  43166. for (var col = 0; col < subdivisionsX; col++) {
  43167. 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) };
  43168. this._heightQuads[row * subdivisionsX + col] = quad;
  43169. }
  43170. }
  43171. return this;
  43172. };
  43173. // Compute each quad element values and update the the heightMap array :
  43174. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43175. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43176. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43177. // Returns the GroundMesh.
  43178. GroundMesh.prototype._computeHeightQuads = function () {
  43179. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43180. var v1 = BABYLON.Tmp.Vector3[3];
  43181. var v2 = BABYLON.Tmp.Vector3[2];
  43182. var v3 = BABYLON.Tmp.Vector3[1];
  43183. var v4 = BABYLON.Tmp.Vector3[0];
  43184. var v1v2 = BABYLON.Tmp.Vector3[4];
  43185. var v1v3 = BABYLON.Tmp.Vector3[5];
  43186. var v1v4 = BABYLON.Tmp.Vector3[6];
  43187. var norm1 = BABYLON.Tmp.Vector3[7];
  43188. var norm2 = BABYLON.Tmp.Vector3[8];
  43189. var i = 0;
  43190. var j = 0;
  43191. var k = 0;
  43192. var cd = 0; // 2D slope coefficient : z = cd * x + h
  43193. var h = 0;
  43194. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  43195. var d2 = 0;
  43196. var subdivisionsX = this._subdivisionsX;
  43197. var subdivisionsY = this._subdivisionsY;
  43198. for (var row = 0; row < subdivisionsY; row++) {
  43199. for (var col = 0; col < subdivisionsX; col++) {
  43200. i = col * 3;
  43201. j = row * (subdivisionsX + 1) * 3;
  43202. k = (row + 1) * (subdivisionsX + 1) * 3;
  43203. v1.x = positions[j + i];
  43204. v1.y = positions[j + i + 1];
  43205. v1.z = positions[j + i + 2];
  43206. v2.x = positions[j + i + 3];
  43207. v2.y = positions[j + i + 4];
  43208. v2.z = positions[j + i + 5];
  43209. v3.x = positions[k + i];
  43210. v3.y = positions[k + i + 1];
  43211. v3.z = positions[k + i + 2];
  43212. v4.x = positions[k + i + 3];
  43213. v4.y = positions[k + i + 4];
  43214. v4.z = positions[k + i + 5];
  43215. // 2D slope V1V4
  43216. cd = (v4.z - v1.z) / (v4.x - v1.x);
  43217. h = v1.z - cd * v1.x; // v1 belongs to the slope
  43218. // facet equations :
  43219. // we compute each facet normal vector
  43220. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  43221. // we compute the value d by applying the equation to v1 which belongs to the plane
  43222. // then we store the facet equation in a Vector4
  43223. v2.subtractToRef(v1, v1v2);
  43224. v3.subtractToRef(v1, v1v3);
  43225. v4.subtractToRef(v1, v1v4);
  43226. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  43227. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  43228. norm1.normalize();
  43229. norm2.normalize();
  43230. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  43231. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  43232. var quad = this._heightQuads[row * subdivisionsX + col];
  43233. quad.slope.copyFromFloats(cd, h);
  43234. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  43235. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  43236. }
  43237. }
  43238. return this;
  43239. };
  43240. GroundMesh.prototype.serialize = function (serializationObject) {
  43241. _super.prototype.serialize.call(this, serializationObject);
  43242. serializationObject.subdivisionsX = this._subdivisionsX;
  43243. serializationObject.subdivisionsY = this._subdivisionsY;
  43244. serializationObject.minX = this._minX;
  43245. serializationObject.maxX = this._maxX;
  43246. serializationObject.minZ = this._minZ;
  43247. serializationObject.maxZ = this._maxZ;
  43248. serializationObject.width = this._width;
  43249. serializationObject.height = this._height;
  43250. };
  43251. GroundMesh.Parse = function (parsedMesh, scene) {
  43252. var result = new GroundMesh(parsedMesh.name, scene);
  43253. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  43254. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  43255. result._minX = parsedMesh.minX;
  43256. result._maxX = parsedMesh.maxX;
  43257. result._minZ = parsedMesh.minZ;
  43258. result._maxZ = parsedMesh.maxZ;
  43259. result._width = parsedMesh.width;
  43260. result._height = parsedMesh.height;
  43261. return result;
  43262. };
  43263. return GroundMesh;
  43264. }(BABYLON.Mesh));
  43265. BABYLON.GroundMesh = GroundMesh;
  43266. })(BABYLON || (BABYLON = {}));
  43267. //# sourceMappingURL=babylon.groundMesh.js.map
  43268. /// <reference path="babylon.mesh.ts" />
  43269. var BABYLON;
  43270. (function (BABYLON) {
  43271. var LinesMesh = (function (_super) {
  43272. __extends(LinesMesh, _super);
  43273. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  43274. if (parent === void 0) { parent = null; }
  43275. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  43276. _this.color = new BABYLON.Color3(1, 1, 1);
  43277. _this.alpha = 1;
  43278. _this._positionBuffer = {};
  43279. if (source) {
  43280. _this.color = source.color.clone();
  43281. _this.alpha = source.alpha;
  43282. }
  43283. _this._intersectionThreshold = 0.1;
  43284. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  43285. attributes: [BABYLON.VertexBuffer.PositionKind],
  43286. uniforms: ["worldViewProjection", "color"],
  43287. needAlphaBlending: true
  43288. });
  43289. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  43290. return _this;
  43291. }
  43292. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  43293. /**
  43294. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43295. * This margin is expressed in world space coordinates, so its value may vary.
  43296. * Default value is 0.1
  43297. * @returns the intersection Threshold value.
  43298. */
  43299. get: function () {
  43300. return this._intersectionThreshold;
  43301. },
  43302. /**
  43303. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43304. * This margin is expressed in world space coordinates, so its value may vary.
  43305. * @param value the new threshold to apply
  43306. */
  43307. set: function (value) {
  43308. if (this._intersectionThreshold === value) {
  43309. return;
  43310. }
  43311. this._intersectionThreshold = value;
  43312. if (this.geometry) {
  43313. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  43314. }
  43315. },
  43316. enumerable: true,
  43317. configurable: true
  43318. });
  43319. /**
  43320. * Returns the string "LineMesh"
  43321. */
  43322. LinesMesh.prototype.getClassName = function () {
  43323. return "LinesMesh";
  43324. };
  43325. Object.defineProperty(LinesMesh.prototype, "material", {
  43326. get: function () {
  43327. return this._colorShader;
  43328. },
  43329. enumerable: true,
  43330. configurable: true
  43331. });
  43332. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  43333. get: function () {
  43334. return false;
  43335. },
  43336. enumerable: true,
  43337. configurable: true
  43338. });
  43339. LinesMesh.prototype.createInstance = function (name) {
  43340. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  43341. return null;
  43342. };
  43343. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  43344. var engine = this.getScene().getEngine();
  43345. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  43346. // VBOs
  43347. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  43348. // Color
  43349. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  43350. return this;
  43351. };
  43352. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  43353. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  43354. return this;
  43355. }
  43356. var engine = this.getScene().getEngine();
  43357. // Draw order
  43358. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  43359. return this;
  43360. };
  43361. LinesMesh.prototype.dispose = function (doNotRecurse) {
  43362. this._colorShader.dispose();
  43363. _super.prototype.dispose.call(this, doNotRecurse);
  43364. };
  43365. /**
  43366. * Returns a new LineMesh object cloned from the current one.
  43367. */
  43368. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43369. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  43370. };
  43371. return LinesMesh;
  43372. }(BABYLON.Mesh));
  43373. BABYLON.LinesMesh = LinesMesh;
  43374. })(BABYLON || (BABYLON = {}));
  43375. //# sourceMappingURL=babylon.linesMesh.js.map
  43376. var BABYLON;
  43377. (function (BABYLON) {
  43378. var DefaultLoadingScreen = (function () {
  43379. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  43380. if (_loadingText === void 0) { _loadingText = ""; }
  43381. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  43382. var _this = this;
  43383. this._renderingCanvas = _renderingCanvas;
  43384. this._loadingText = _loadingText;
  43385. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  43386. // Resize
  43387. this._resizeLoadingUI = function () {
  43388. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  43389. _this._loadingDiv.style.position = "absolute";
  43390. _this._loadingDiv.style.left = canvasRect.left + "px";
  43391. _this._loadingDiv.style.top = canvasRect.top + "px";
  43392. _this._loadingDiv.style.width = canvasRect.width + "px";
  43393. _this._loadingDiv.style.height = canvasRect.height + "px";
  43394. };
  43395. }
  43396. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  43397. var _this = this;
  43398. if (this._loadingDiv) {
  43399. // Do not add a loading screen if there is already one
  43400. return;
  43401. }
  43402. this._loadingDiv = document.createElement("div");
  43403. this._loadingDiv.id = "babylonjsLoadingDiv";
  43404. this._loadingDiv.style.opacity = "0";
  43405. this._loadingDiv.style.transition = "opacity 1.5s ease";
  43406. // Loading text
  43407. this._loadingTextDiv = document.createElement("div");
  43408. this._loadingTextDiv.style.position = "absolute";
  43409. this._loadingTextDiv.style.left = "0";
  43410. this._loadingTextDiv.style.top = "50%";
  43411. this._loadingTextDiv.style.marginTop = "80px";
  43412. this._loadingTextDiv.style.width = "100%";
  43413. this._loadingTextDiv.style.height = "20px";
  43414. this._loadingTextDiv.style.fontFamily = "Arial";
  43415. this._loadingTextDiv.style.fontSize = "14px";
  43416. this._loadingTextDiv.style.color = "white";
  43417. this._loadingTextDiv.style.textAlign = "center";
  43418. this._loadingTextDiv.innerHTML = "Loading";
  43419. this._loadingDiv.appendChild(this._loadingTextDiv);
  43420. //set the predefined text
  43421. this._loadingTextDiv.innerHTML = this._loadingText;
  43422. // Loading img
  43423. var imgBack = new Image();
  43424. 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==";
  43425. imgBack.style.position = "absolute";
  43426. imgBack.style.left = "50%";
  43427. imgBack.style.top = "50%";
  43428. imgBack.style.marginLeft = "-50px";
  43429. imgBack.style.marginTop = "-50px";
  43430. imgBack.style.transition = "transform 1.0s ease";
  43431. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  43432. var deg = 360;
  43433. var onTransitionEnd = function () {
  43434. deg += 360;
  43435. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  43436. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  43437. };
  43438. imgBack.addEventListener("transitionend", onTransitionEnd);
  43439. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  43440. this._loadingDiv.appendChild(imgBack);
  43441. // front image
  43442. var imgFront = new Image();
  43443. 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=";
  43444. imgFront.style.position = "absolute";
  43445. imgFront.style.left = "50%";
  43446. imgFront.style.top = "50%";
  43447. imgFront.style.marginLeft = "-50px";
  43448. imgFront.style.marginTop = "-50px";
  43449. this._loadingDiv.appendChild(imgFront);
  43450. this._resizeLoadingUI();
  43451. window.addEventListener("resize", this._resizeLoadingUI);
  43452. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  43453. document.body.appendChild(this._loadingDiv);
  43454. setTimeout(function () {
  43455. _this._loadingDiv.style.opacity = "1";
  43456. imgBack.style.transform = "rotateZ(360deg)";
  43457. imgBack.style.webkitTransform = "rotateZ(360deg)";
  43458. }, 0);
  43459. };
  43460. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  43461. var _this = this;
  43462. if (!this._loadingDiv) {
  43463. return;
  43464. }
  43465. var onTransitionEnd = function () {
  43466. if (!_this._loadingDiv) {
  43467. return;
  43468. }
  43469. document.body.removeChild(_this._loadingDiv);
  43470. window.removeEventListener("resize", _this._resizeLoadingUI);
  43471. _this._loadingDiv = null;
  43472. };
  43473. this._loadingDiv.style.opacity = "0";
  43474. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  43475. };
  43476. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  43477. set: function (text) {
  43478. this._loadingText = text;
  43479. if (this._loadingTextDiv) {
  43480. this._loadingTextDiv.innerHTML = this._loadingText;
  43481. }
  43482. },
  43483. enumerable: true,
  43484. configurable: true
  43485. });
  43486. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  43487. get: function () {
  43488. return this._loadingDivBackgroundColor;
  43489. },
  43490. set: function (color) {
  43491. this._loadingDivBackgroundColor = color;
  43492. if (!this._loadingDiv) {
  43493. return;
  43494. }
  43495. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  43496. },
  43497. enumerable: true,
  43498. configurable: true
  43499. });
  43500. return DefaultLoadingScreen;
  43501. }());
  43502. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  43503. })(BABYLON || (BABYLON = {}));
  43504. //# sourceMappingURL=babylon.loadingScreen.js.map
  43505. var BABYLON;
  43506. (function (BABYLON) {
  43507. var AudioEngine = (function () {
  43508. function AudioEngine() {
  43509. this._audioContext = null;
  43510. this._audioContextInitialized = false;
  43511. this.canUseWebAudio = false;
  43512. this.WarnedWebAudioUnsupported = false;
  43513. this.unlocked = false;
  43514. this.isMP3supported = false;
  43515. this.isOGGsupported = false;
  43516. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  43517. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  43518. this.canUseWebAudio = true;
  43519. }
  43520. var audioElem = document.createElement('audio');
  43521. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  43522. this.isMP3supported = true;
  43523. }
  43524. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  43525. this.isOGGsupported = true;
  43526. }
  43527. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  43528. this._unlockiOSaudio();
  43529. }
  43530. else {
  43531. this.unlocked = true;
  43532. }
  43533. }
  43534. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  43535. get: function () {
  43536. if (!this._audioContextInitialized) {
  43537. this._initializeAudioContext();
  43538. }
  43539. return this._audioContext;
  43540. },
  43541. enumerable: true,
  43542. configurable: true
  43543. });
  43544. AudioEngine.prototype._unlockiOSaudio = function () {
  43545. var _this = this;
  43546. var unlockaudio = function () {
  43547. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  43548. var source = _this.audioContext.createBufferSource();
  43549. source.buffer = buffer;
  43550. source.connect(_this.audioContext.destination);
  43551. source.start(0);
  43552. setTimeout(function () {
  43553. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  43554. _this.unlocked = true;
  43555. window.removeEventListener('touchend', unlockaudio, false);
  43556. if (_this.onAudioUnlocked) {
  43557. _this.onAudioUnlocked();
  43558. }
  43559. }
  43560. }, 0);
  43561. };
  43562. window.addEventListener('touchend', unlockaudio, false);
  43563. };
  43564. AudioEngine.prototype._initializeAudioContext = function () {
  43565. try {
  43566. if (this.canUseWebAudio) {
  43567. this._audioContext = new AudioContext();
  43568. // create a global volume gain node
  43569. this.masterGain = this._audioContext.createGain();
  43570. this.masterGain.gain.value = 1;
  43571. this.masterGain.connect(this._audioContext.destination);
  43572. this._audioContextInitialized = true;
  43573. }
  43574. }
  43575. catch (e) {
  43576. this.canUseWebAudio = false;
  43577. BABYLON.Tools.Error("Web Audio: " + e.message);
  43578. }
  43579. };
  43580. AudioEngine.prototype.dispose = function () {
  43581. if (this.canUseWebAudio && this._audioContextInitialized) {
  43582. if (this._connectedAnalyser) {
  43583. this._connectedAnalyser.stopDebugCanvas();
  43584. this._connectedAnalyser.dispose();
  43585. this.masterGain.disconnect();
  43586. this.masterGain.connect(this._audioContext.destination);
  43587. this._connectedAnalyser = null;
  43588. }
  43589. this.masterGain.gain.value = 1;
  43590. }
  43591. this.WarnedWebAudioUnsupported = false;
  43592. };
  43593. AudioEngine.prototype.getGlobalVolume = function () {
  43594. if (this.canUseWebAudio && this._audioContextInitialized) {
  43595. return this.masterGain.gain.value;
  43596. }
  43597. else {
  43598. return -1;
  43599. }
  43600. };
  43601. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  43602. if (this.canUseWebAudio && this._audioContextInitialized) {
  43603. this.masterGain.gain.value = newVolume;
  43604. }
  43605. };
  43606. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  43607. if (this._connectedAnalyser) {
  43608. this._connectedAnalyser.stopDebugCanvas();
  43609. }
  43610. if (this.canUseWebAudio && this._audioContextInitialized) {
  43611. this._connectedAnalyser = analyser;
  43612. this.masterGain.disconnect();
  43613. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  43614. }
  43615. };
  43616. return AudioEngine;
  43617. }());
  43618. BABYLON.AudioEngine = AudioEngine;
  43619. })(BABYLON || (BABYLON = {}));
  43620. //# sourceMappingURL=babylon.audioEngine.js.map
  43621. var BABYLON;
  43622. (function (BABYLON) {
  43623. var Sound = (function () {
  43624. /**
  43625. * Create a sound and attach it to a scene
  43626. * @param name Name of your sound
  43627. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  43628. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  43629. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  43630. */
  43631. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  43632. var _this = this;
  43633. this.autoplay = false;
  43634. this.loop = false;
  43635. this.useCustomAttenuation = false;
  43636. this.spatialSound = false;
  43637. this.refDistance = 1;
  43638. this.rolloffFactor = 1;
  43639. this.maxDistance = 100;
  43640. this.distanceModel = "linear";
  43641. this._panningModel = "equalpower";
  43642. this._playbackRate = 1;
  43643. this._streaming = false;
  43644. this._startTime = 0;
  43645. this._startOffset = 0;
  43646. this._position = BABYLON.Vector3.Zero();
  43647. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  43648. this._volume = 1;
  43649. this._isLoaded = false;
  43650. this._isReadyToPlay = false;
  43651. this.isPlaying = false;
  43652. this.isPaused = false;
  43653. this._isDirectional = false;
  43654. // Used if you'd like to create a directional sound.
  43655. // If not set, the sound will be omnidirectional
  43656. this._coneInnerAngle = 360;
  43657. this._coneOuterAngle = 360;
  43658. this._coneOuterGain = 0;
  43659. this._isOutputConnected = false;
  43660. this._urlType = "Unknown";
  43661. this.name = name;
  43662. this._scene = scene;
  43663. this._readyToPlayCallback = readyToPlayCallback;
  43664. // Default custom attenuation function is a linear attenuation
  43665. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  43666. if (currentDistance < maxDistance) {
  43667. return currentVolume * (1 - currentDistance / maxDistance);
  43668. }
  43669. else {
  43670. return 0;
  43671. }
  43672. };
  43673. if (options) {
  43674. this.autoplay = options.autoplay || false;
  43675. this.loop = options.loop || false;
  43676. // if volume === 0, we need another way to check this option
  43677. if (options.volume !== undefined) {
  43678. this._volume = options.volume;
  43679. }
  43680. this.spatialSound = options.spatialSound || false;
  43681. this.maxDistance = options.maxDistance || 100;
  43682. this.useCustomAttenuation = options.useCustomAttenuation || false;
  43683. this.rolloffFactor = options.rolloffFactor || 1;
  43684. this.refDistance = options.refDistance || 1;
  43685. this.distanceModel = options.distanceModel || "linear";
  43686. this._playbackRate = options.playbackRate || 1;
  43687. this._streaming = options.streaming || false;
  43688. }
  43689. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43690. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  43691. this._soundGain.gain.value = this._volume;
  43692. this._inputAudioNode = this._soundGain;
  43693. this._ouputAudioNode = this._soundGain;
  43694. if (this.spatialSound) {
  43695. this._createSpatialParameters();
  43696. }
  43697. this._scene.mainSoundTrack.AddSound(this);
  43698. var validParameter = true;
  43699. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  43700. if (urlOrArrayBuffer) {
  43701. if (typeof (urlOrArrayBuffer) === "string")
  43702. this._urlType = "String";
  43703. if (Array.isArray(urlOrArrayBuffer))
  43704. this._urlType = "Array";
  43705. if (urlOrArrayBuffer instanceof ArrayBuffer)
  43706. this._urlType = "ArrayBuffer";
  43707. var urls = [];
  43708. var codecSupportedFound = false;
  43709. switch (this._urlType) {
  43710. case "ArrayBuffer":
  43711. if (urlOrArrayBuffer.byteLength > 0) {
  43712. codecSupportedFound = true;
  43713. this._soundLoaded(urlOrArrayBuffer);
  43714. }
  43715. break;
  43716. case "String":
  43717. urls.push(urlOrArrayBuffer);
  43718. case "Array":
  43719. if (urls.length === 0)
  43720. urls = urlOrArrayBuffer;
  43721. // If we found a supported format, we load it immediately and stop the loop
  43722. for (var i = 0; i < urls.length; i++) {
  43723. var url = urls[i];
  43724. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  43725. codecSupportedFound = true;
  43726. }
  43727. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  43728. codecSupportedFound = true;
  43729. }
  43730. if (url.indexOf(".wav", url.length - 4) !== -1) {
  43731. codecSupportedFound = true;
  43732. }
  43733. if (codecSupportedFound) {
  43734. // Loading sound using XHR2
  43735. if (!this._streaming) {
  43736. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  43737. }
  43738. else {
  43739. this._htmlAudioElement = new Audio(url);
  43740. this._htmlAudioElement.controls = false;
  43741. this._htmlAudioElement.loop = this.loop;
  43742. this._htmlAudioElement.crossOrigin = "anonymous";
  43743. this._htmlAudioElement.preload = "auto";
  43744. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  43745. _this._isReadyToPlay = true;
  43746. if (_this.autoplay) {
  43747. _this.play();
  43748. }
  43749. if (_this._readyToPlayCallback) {
  43750. _this._readyToPlayCallback();
  43751. }
  43752. });
  43753. document.body.appendChild(this._htmlAudioElement);
  43754. }
  43755. break;
  43756. }
  43757. }
  43758. break;
  43759. default:
  43760. validParameter = false;
  43761. break;
  43762. }
  43763. if (!validParameter) {
  43764. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  43765. }
  43766. else {
  43767. if (!codecSupportedFound) {
  43768. this._isReadyToPlay = true;
  43769. // Simulating a ready to play event to avoid breaking code path
  43770. if (this._readyToPlayCallback) {
  43771. window.setTimeout(function () {
  43772. _this._readyToPlayCallback();
  43773. }, 1000);
  43774. }
  43775. }
  43776. }
  43777. }
  43778. }
  43779. else {
  43780. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  43781. this._scene.mainSoundTrack.AddSound(this);
  43782. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  43783. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  43784. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  43785. }
  43786. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  43787. if (this._readyToPlayCallback) {
  43788. window.setTimeout(function () {
  43789. _this._readyToPlayCallback();
  43790. }, 1000);
  43791. }
  43792. }
  43793. }
  43794. Sound.prototype.dispose = function () {
  43795. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  43796. if (this.isPlaying) {
  43797. this.stop();
  43798. }
  43799. this._isReadyToPlay = false;
  43800. if (this.soundTrackId === -1) {
  43801. this._scene.mainSoundTrack.RemoveSound(this);
  43802. }
  43803. else {
  43804. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  43805. }
  43806. if (this._soundGain) {
  43807. this._soundGain.disconnect();
  43808. this._soundGain = null;
  43809. }
  43810. if (this._soundPanner) {
  43811. this._soundPanner.disconnect();
  43812. this._soundPanner = null;
  43813. }
  43814. if (this._soundSource) {
  43815. this._soundSource.disconnect();
  43816. this._soundSource = null;
  43817. }
  43818. this._audioBuffer = null;
  43819. if (this._htmlAudioElement) {
  43820. this._htmlAudioElement.pause();
  43821. this._htmlAudioElement.src = "";
  43822. document.body.removeChild(this._htmlAudioElement);
  43823. }
  43824. if (this._connectedMesh) {
  43825. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  43826. this._connectedMesh = null;
  43827. }
  43828. }
  43829. };
  43830. Sound.prototype.isReady = function () {
  43831. return this._isReadyToPlay;
  43832. };
  43833. Sound.prototype._soundLoaded = function (audioData) {
  43834. var _this = this;
  43835. this._isLoaded = true;
  43836. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  43837. _this._audioBuffer = buffer;
  43838. _this._isReadyToPlay = true;
  43839. if (_this.autoplay) {
  43840. _this.play();
  43841. }
  43842. if (_this._readyToPlayCallback) {
  43843. _this._readyToPlayCallback();
  43844. }
  43845. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  43846. };
  43847. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  43848. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43849. this._audioBuffer = audioBuffer;
  43850. this._isReadyToPlay = true;
  43851. }
  43852. };
  43853. Sound.prototype.updateOptions = function (options) {
  43854. if (options) {
  43855. this.loop = options.loop || this.loop;
  43856. this.maxDistance = options.maxDistance || this.maxDistance;
  43857. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  43858. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  43859. this.refDistance = options.refDistance || this.refDistance;
  43860. this.distanceModel = options.distanceModel || this.distanceModel;
  43861. this._playbackRate = options.playbackRate || this._playbackRate;
  43862. this._updateSpatialParameters();
  43863. if (this.isPlaying) {
  43864. if (this._streaming) {
  43865. this._htmlAudioElement.playbackRate = this._playbackRate;
  43866. }
  43867. else {
  43868. this._soundSource.playbackRate.value = this._playbackRate;
  43869. }
  43870. }
  43871. }
  43872. };
  43873. Sound.prototype._createSpatialParameters = function () {
  43874. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43875. if (this._scene.headphone) {
  43876. this._panningModel = "HRTF";
  43877. }
  43878. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  43879. this._updateSpatialParameters();
  43880. this._soundPanner.connect(this._ouputAudioNode);
  43881. this._inputAudioNode = this._soundPanner;
  43882. }
  43883. };
  43884. Sound.prototype._updateSpatialParameters = function () {
  43885. if (this.spatialSound) {
  43886. if (this.useCustomAttenuation) {
  43887. // Tricks to disable in a way embedded Web Audio attenuation
  43888. this._soundPanner.distanceModel = "linear";
  43889. this._soundPanner.maxDistance = Number.MAX_VALUE;
  43890. this._soundPanner.refDistance = 1;
  43891. this._soundPanner.rolloffFactor = 1;
  43892. this._soundPanner.panningModel = this._panningModel;
  43893. }
  43894. else {
  43895. this._soundPanner.distanceModel = this.distanceModel;
  43896. this._soundPanner.maxDistance = this.maxDistance;
  43897. this._soundPanner.refDistance = this.refDistance;
  43898. this._soundPanner.rolloffFactor = this.rolloffFactor;
  43899. this._soundPanner.panningModel = this._panningModel;
  43900. }
  43901. }
  43902. };
  43903. Sound.prototype.switchPanningModelToHRTF = function () {
  43904. this._panningModel = "HRTF";
  43905. this._switchPanningModel();
  43906. };
  43907. Sound.prototype.switchPanningModelToEqualPower = function () {
  43908. this._panningModel = "equalpower";
  43909. this._switchPanningModel();
  43910. };
  43911. Sound.prototype._switchPanningModel = function () {
  43912. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  43913. this._soundPanner.panningModel = this._panningModel;
  43914. }
  43915. };
  43916. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  43917. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43918. if (this._isOutputConnected) {
  43919. this._ouputAudioNode.disconnect();
  43920. }
  43921. this._ouputAudioNode.connect(soundTrackAudioNode);
  43922. this._isOutputConnected = true;
  43923. }
  43924. };
  43925. /**
  43926. * Transform this sound into a directional source
  43927. * @param coneInnerAngle Size of the inner cone in degree
  43928. * @param coneOuterAngle Size of the outer cone in degree
  43929. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  43930. */
  43931. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  43932. if (coneOuterAngle < coneInnerAngle) {
  43933. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  43934. return;
  43935. }
  43936. this._coneInnerAngle = coneInnerAngle;
  43937. this._coneOuterAngle = coneOuterAngle;
  43938. this._coneOuterGain = coneOuterGain;
  43939. this._isDirectional = true;
  43940. if (this.isPlaying && this.loop) {
  43941. this.stop();
  43942. this.play();
  43943. }
  43944. };
  43945. Sound.prototype.setPosition = function (newPosition) {
  43946. this._position = newPosition;
  43947. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  43948. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  43949. }
  43950. };
  43951. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  43952. this._localDirection = newLocalDirection;
  43953. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  43954. this._updateDirection();
  43955. }
  43956. };
  43957. Sound.prototype._updateDirection = function () {
  43958. var mat = this._connectedMesh.getWorldMatrix();
  43959. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  43960. direction.normalize();
  43961. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  43962. };
  43963. Sound.prototype.updateDistanceFromListener = function () {
  43964. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  43965. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  43966. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  43967. }
  43968. };
  43969. Sound.prototype.setAttenuationFunction = function (callback) {
  43970. this._customAttenuationFunction = callback;
  43971. };
  43972. /**
  43973. * Play the sound
  43974. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  43975. * @param offset (optional) Start the sound setting it at a specific time
  43976. */
  43977. Sound.prototype.play = function (time, offset) {
  43978. var _this = this;
  43979. if (this._isReadyToPlay && this._scene.audioEnabled) {
  43980. try {
  43981. if (this._startOffset < 0) {
  43982. time = -this._startOffset;
  43983. this._startOffset = 0;
  43984. }
  43985. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  43986. if (!this._soundSource || !this._streamingSource) {
  43987. if (this.spatialSound) {
  43988. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  43989. if (this._isDirectional) {
  43990. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  43991. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  43992. this._soundPanner.coneOuterGain = this._coneOuterGain;
  43993. if (this._connectedMesh) {
  43994. this._updateDirection();
  43995. }
  43996. else {
  43997. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  43998. }
  43999. }
  44000. }
  44001. }
  44002. if (this._streaming) {
  44003. if (!this._streamingSource) {
  44004. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  44005. this._htmlAudioElement.onended = function () { _this._onended(); };
  44006. this._htmlAudioElement.playbackRate = this._playbackRate;
  44007. }
  44008. this._streamingSource.disconnect();
  44009. this._streamingSource.connect(this._inputAudioNode);
  44010. this._htmlAudioElement.play();
  44011. }
  44012. else {
  44013. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  44014. this._soundSource.buffer = this._audioBuffer;
  44015. this._soundSource.connect(this._inputAudioNode);
  44016. this._soundSource.loop = this.loop;
  44017. this._soundSource.playbackRate.value = this._playbackRate;
  44018. this._soundSource.onended = function () { _this._onended(); };
  44019. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  44020. }
  44021. this._startTime = startTime;
  44022. this.isPlaying = true;
  44023. this.isPaused = false;
  44024. }
  44025. catch (ex) {
  44026. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  44027. }
  44028. }
  44029. };
  44030. Sound.prototype._onended = function () {
  44031. this.isPlaying = false;
  44032. if (this.onended) {
  44033. this.onended();
  44034. }
  44035. };
  44036. /**
  44037. * Stop the sound
  44038. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  44039. */
  44040. Sound.prototype.stop = function (time) {
  44041. if (this.isPlaying) {
  44042. if (this._streaming) {
  44043. this._htmlAudioElement.pause();
  44044. // Test needed for Firefox or it will generate an Invalid State Error
  44045. if (this._htmlAudioElement.currentTime > 0) {
  44046. this._htmlAudioElement.currentTime = 0;
  44047. }
  44048. }
  44049. else {
  44050. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  44051. this._soundSource.stop(stopTime);
  44052. this._soundSource.onended = null;
  44053. if (!this.isPaused) {
  44054. this._startOffset = 0;
  44055. }
  44056. }
  44057. this.isPlaying = false;
  44058. }
  44059. };
  44060. Sound.prototype.pause = function () {
  44061. if (this.isPlaying) {
  44062. this.isPaused = true;
  44063. if (this._streaming) {
  44064. this._htmlAudioElement.pause();
  44065. }
  44066. else {
  44067. this.stop(0);
  44068. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  44069. }
  44070. }
  44071. };
  44072. Sound.prototype.setVolume = function (newVolume, time) {
  44073. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44074. if (time) {
  44075. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  44076. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  44077. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  44078. }
  44079. else {
  44080. this._soundGain.gain.value = newVolume;
  44081. }
  44082. }
  44083. this._volume = newVolume;
  44084. };
  44085. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  44086. this._playbackRate = newPlaybackRate;
  44087. if (this.isPlaying) {
  44088. if (this._streaming) {
  44089. this._htmlAudioElement.playbackRate = this._playbackRate;
  44090. }
  44091. else {
  44092. this._soundSource.playbackRate.value = this._playbackRate;
  44093. }
  44094. }
  44095. };
  44096. Sound.prototype.getVolume = function () {
  44097. return this._volume;
  44098. };
  44099. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  44100. var _this = this;
  44101. if (this._connectedMesh) {
  44102. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44103. this._registerFunc = null;
  44104. }
  44105. this._connectedMesh = meshToConnectTo;
  44106. if (!this.spatialSound) {
  44107. this.spatialSound = true;
  44108. this._createSpatialParameters();
  44109. if (this.isPlaying && this.loop) {
  44110. this.stop();
  44111. this.play();
  44112. }
  44113. }
  44114. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  44115. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  44116. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  44117. };
  44118. Sound.prototype.detachFromMesh = function () {
  44119. if (this._connectedMesh) {
  44120. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44121. this._registerFunc = null;
  44122. this._connectedMesh = null;
  44123. }
  44124. };
  44125. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  44126. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  44127. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  44128. this._updateDirection();
  44129. }
  44130. };
  44131. Sound.prototype.clone = function () {
  44132. var _this = this;
  44133. if (!this._streaming) {
  44134. var setBufferAndRun = function () {
  44135. if (_this._isReadyToPlay) {
  44136. clonedSound._audioBuffer = _this.getAudioBuffer();
  44137. clonedSound._isReadyToPlay = true;
  44138. if (clonedSound.autoplay) {
  44139. clonedSound.play();
  44140. }
  44141. }
  44142. else {
  44143. window.setTimeout(setBufferAndRun, 300);
  44144. }
  44145. };
  44146. var currentOptions = {
  44147. autoplay: this.autoplay, loop: this.loop,
  44148. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  44149. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  44150. refDistance: this.refDistance, distanceModel: this.distanceModel
  44151. };
  44152. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  44153. if (this.useCustomAttenuation) {
  44154. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  44155. }
  44156. clonedSound.setPosition(this._position);
  44157. clonedSound.setPlaybackRate(this._playbackRate);
  44158. setBufferAndRun();
  44159. return clonedSound;
  44160. }
  44161. else {
  44162. return null;
  44163. }
  44164. };
  44165. Sound.prototype.getAudioBuffer = function () {
  44166. return this._audioBuffer;
  44167. };
  44168. Sound.prototype.serialize = function () {
  44169. var serializationObject = {
  44170. name: this.name,
  44171. url: this.name,
  44172. autoplay: this.autoplay,
  44173. loop: this.loop,
  44174. volume: this._volume,
  44175. spatialSound: this.spatialSound,
  44176. maxDistance: this.maxDistance,
  44177. rolloffFactor: this.rolloffFactor,
  44178. refDistance: this.refDistance,
  44179. distanceModel: this.distanceModel,
  44180. playbackRate: this._playbackRate,
  44181. panningModel: this._panningModel,
  44182. soundTrackId: this.soundTrackId
  44183. };
  44184. if (this.spatialSound) {
  44185. if (this._connectedMesh)
  44186. serializationObject.connectedMeshId = this._connectedMesh.id;
  44187. serializationObject.position = this._position.asArray();
  44188. serializationObject.refDistance = this.refDistance;
  44189. serializationObject.distanceModel = this.distanceModel;
  44190. serializationObject.isDirectional = this._isDirectional;
  44191. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  44192. serializationObject.coneInnerAngle = this._coneInnerAngle;
  44193. serializationObject.coneOuterAngle = this._coneOuterAngle;
  44194. serializationObject.coneOuterGain = this._coneOuterGain;
  44195. }
  44196. return serializationObject;
  44197. };
  44198. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  44199. var soundName = parsedSound.name;
  44200. var soundUrl;
  44201. if (parsedSound.url) {
  44202. soundUrl = rootUrl + parsedSound.url;
  44203. }
  44204. else {
  44205. soundUrl = rootUrl + soundName;
  44206. }
  44207. var options = {
  44208. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  44209. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  44210. rolloffFactor: parsedSound.rolloffFactor,
  44211. refDistance: parsedSound.refDistance,
  44212. distanceModel: parsedSound.distanceModel,
  44213. playbackRate: parsedSound.playbackRate
  44214. };
  44215. var newSound;
  44216. if (!sourceSound) {
  44217. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  44218. scene._addPendingData(newSound);
  44219. }
  44220. else {
  44221. var setBufferAndRun = function () {
  44222. if (sourceSound._isReadyToPlay) {
  44223. newSound._audioBuffer = sourceSound.getAudioBuffer();
  44224. newSound._isReadyToPlay = true;
  44225. if (newSound.autoplay) {
  44226. newSound.play();
  44227. }
  44228. }
  44229. else {
  44230. window.setTimeout(setBufferAndRun, 300);
  44231. }
  44232. };
  44233. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  44234. setBufferAndRun();
  44235. }
  44236. if (parsedSound.position) {
  44237. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  44238. newSound.setPosition(soundPosition);
  44239. }
  44240. if (parsedSound.isDirectional) {
  44241. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  44242. if (parsedSound.localDirectionToMesh) {
  44243. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  44244. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  44245. }
  44246. }
  44247. if (parsedSound.connectedMeshId) {
  44248. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  44249. if (connectedMesh) {
  44250. newSound.attachToMesh(connectedMesh);
  44251. }
  44252. }
  44253. return newSound;
  44254. };
  44255. return Sound;
  44256. }());
  44257. BABYLON.Sound = Sound;
  44258. })(BABYLON || (BABYLON = {}));
  44259. //# sourceMappingURL=babylon.sound.js.map
  44260. var BABYLON;
  44261. (function (BABYLON) {
  44262. var SoundTrack = (function () {
  44263. function SoundTrack(scene, options) {
  44264. this.id = -1;
  44265. this._isMainTrack = false;
  44266. this._isInitialized = false;
  44267. this._scene = scene;
  44268. this.soundCollection = new Array();
  44269. this._options = options;
  44270. if (!this._isMainTrack) {
  44271. this._scene.soundTracks.push(this);
  44272. this.id = this._scene.soundTracks.length - 1;
  44273. }
  44274. }
  44275. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  44276. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44277. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  44278. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  44279. if (this._options) {
  44280. if (this._options.volume) {
  44281. this._outputAudioNode.gain.value = this._options.volume;
  44282. }
  44283. if (this._options.mainTrack) {
  44284. this._isMainTrack = this._options.mainTrack;
  44285. }
  44286. }
  44287. this._isInitialized = true;
  44288. }
  44289. };
  44290. SoundTrack.prototype.dispose = function () {
  44291. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44292. if (this._connectedAnalyser) {
  44293. this._connectedAnalyser.stopDebugCanvas();
  44294. }
  44295. while (this.soundCollection.length) {
  44296. this.soundCollection[0].dispose();
  44297. }
  44298. if (this._outputAudioNode) {
  44299. this._outputAudioNode.disconnect();
  44300. }
  44301. this._outputAudioNode = null;
  44302. }
  44303. };
  44304. SoundTrack.prototype.AddSound = function (sound) {
  44305. if (!this._isInitialized) {
  44306. this._initializeSoundTrackAudioGraph();
  44307. }
  44308. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44309. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  44310. }
  44311. if (sound.soundTrackId) {
  44312. if (sound.soundTrackId === -1) {
  44313. this._scene.mainSoundTrack.RemoveSound(sound);
  44314. }
  44315. else {
  44316. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  44317. }
  44318. }
  44319. this.soundCollection.push(sound);
  44320. sound.soundTrackId = this.id;
  44321. };
  44322. SoundTrack.prototype.RemoveSound = function (sound) {
  44323. var index = this.soundCollection.indexOf(sound);
  44324. if (index !== -1) {
  44325. this.soundCollection.splice(index, 1);
  44326. }
  44327. };
  44328. SoundTrack.prototype.setVolume = function (newVolume) {
  44329. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44330. this._outputAudioNode.gain.value = newVolume;
  44331. }
  44332. };
  44333. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  44334. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44335. for (var i = 0; i < this.soundCollection.length; i++) {
  44336. this.soundCollection[i].switchPanningModelToHRTF();
  44337. }
  44338. }
  44339. };
  44340. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  44341. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44342. for (var i = 0; i < this.soundCollection.length; i++) {
  44343. this.soundCollection[i].switchPanningModelToEqualPower();
  44344. }
  44345. }
  44346. };
  44347. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  44348. if (this._connectedAnalyser) {
  44349. this._connectedAnalyser.stopDebugCanvas();
  44350. }
  44351. this._connectedAnalyser = analyser;
  44352. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44353. this._outputAudioNode.disconnect();
  44354. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  44355. }
  44356. };
  44357. return SoundTrack;
  44358. }());
  44359. BABYLON.SoundTrack = SoundTrack;
  44360. })(BABYLON || (BABYLON = {}));
  44361. //# sourceMappingURL=babylon.soundtrack.js.map
  44362. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  44363. /// <reference path="..\Math\babylon.math.ts" />
  44364. var BABYLON;
  44365. (function (BABYLON) {
  44366. /**
  44367. * Special Glow Blur post process only blurring the alpha channel
  44368. * It enforces keeping the most luminous color in the color channel.
  44369. */
  44370. var GlowBlurPostProcess = (function (_super) {
  44371. __extends(GlowBlurPostProcess, _super);
  44372. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  44373. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  44374. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  44375. _this.direction = direction;
  44376. _this.blurWidth = blurWidth;
  44377. _this.onApplyObservable.add(function (effect) {
  44378. effect.setFloat2("screenSize", _this.width, _this.height);
  44379. effect.setVector2("direction", _this.direction);
  44380. effect.setFloat("blurWidth", _this.blurWidth);
  44381. });
  44382. return _this;
  44383. }
  44384. return GlowBlurPostProcess;
  44385. }(BABYLON.PostProcess));
  44386. /**
  44387. * The highlight layer Helps adding a glow effect around a mesh.
  44388. *
  44389. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  44390. * glowy meshes to your scene.
  44391. *
  44392. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  44393. */
  44394. var HighlightLayer = (function () {
  44395. /**
  44396. * Instantiates a new highlight Layer and references it to the scene..
  44397. * @param name The name of the layer
  44398. * @param scene The scene to use the layer in
  44399. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  44400. */
  44401. function HighlightLayer(name, scene, options) {
  44402. this.name = name;
  44403. this._vertexBuffers = {};
  44404. this._mainTextureDesiredSize = { width: 0, height: 0 };
  44405. this._meshes = {};
  44406. this._maxSize = 0;
  44407. this._shouldRender = false;
  44408. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  44409. this._excludedMeshes = {};
  44410. /**
  44411. * Specifies whether or not the inner glow is ACTIVE in the layer.
  44412. */
  44413. this.innerGlow = true;
  44414. /**
  44415. * Specifies whether or not the outer glow is ACTIVE in the layer.
  44416. */
  44417. this.outerGlow = true;
  44418. /**
  44419. * Specifies wether the highlight layer is enabled or not.
  44420. */
  44421. this.isEnabled = true;
  44422. /**
  44423. * An event triggered when the highlight layer has been disposed.
  44424. * @type {BABYLON.Observable}
  44425. */
  44426. this.onDisposeObservable = new BABYLON.Observable();
  44427. /**
  44428. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  44429. * @type {BABYLON.Observable}
  44430. */
  44431. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  44432. /**
  44433. * An event triggered when the highlight layer is being blurred.
  44434. * @type {BABYLON.Observable}
  44435. */
  44436. this.onBeforeBlurObservable = new BABYLON.Observable();
  44437. /**
  44438. * An event triggered when the highlight layer has been blurred.
  44439. * @type {BABYLON.Observable}
  44440. */
  44441. this.onAfterBlurObservable = new BABYLON.Observable();
  44442. /**
  44443. * An event triggered when the glowing blurred texture is being merged in the scene.
  44444. * @type {BABYLON.Observable}
  44445. */
  44446. this.onBeforeComposeObservable = new BABYLON.Observable();
  44447. /**
  44448. * An event triggered when the glowing blurred texture has been merged in the scene.
  44449. * @type {BABYLON.Observable}
  44450. */
  44451. this.onAfterComposeObservable = new BABYLON.Observable();
  44452. /**
  44453. * An event triggered when the highlight layer changes its size.
  44454. * @type {BABYLON.Observable}
  44455. */
  44456. this.onSizeChangedObservable = new BABYLON.Observable();
  44457. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44458. var engine = scene.getEngine();
  44459. this._engine = engine;
  44460. this._maxSize = this._engine.getCaps().maxTextureSize;
  44461. this._scene.highlightLayers.push(this);
  44462. // Warn on stencil.
  44463. if (!this._engine.isStencilEnable) {
  44464. 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 }");
  44465. }
  44466. // Adapt options
  44467. this._options = options || {
  44468. mainTextureRatio: 0.25,
  44469. blurTextureSizeRatio: 0.5,
  44470. blurHorizontalSize: 1,
  44471. blurVerticalSize: 1,
  44472. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  44473. };
  44474. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  44475. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  44476. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  44477. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  44478. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  44479. // VBO
  44480. var vertices = [];
  44481. vertices.push(1, 1);
  44482. vertices.push(-1, 1);
  44483. vertices.push(-1, -1);
  44484. vertices.push(1, -1);
  44485. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  44486. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  44487. // Indices
  44488. var indices = [];
  44489. indices.push(0);
  44490. indices.push(1);
  44491. indices.push(2);
  44492. indices.push(0);
  44493. indices.push(2);
  44494. indices.push(3);
  44495. this._indexBuffer = engine.createIndexBuffer(indices);
  44496. // Effect
  44497. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  44498. // Render target
  44499. this.setMainTextureSize();
  44500. // Create Textures and post processes
  44501. this.createTextureAndPostProcesses();
  44502. }
  44503. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  44504. /**
  44505. * Gets the horizontal size of the blur.
  44506. */
  44507. get: function () {
  44508. return this._horizontalBlurPostprocess.blurWidth;
  44509. },
  44510. /**
  44511. * Specifies the horizontal size of the blur.
  44512. */
  44513. set: function (value) {
  44514. this._horizontalBlurPostprocess.blurWidth = value;
  44515. },
  44516. enumerable: true,
  44517. configurable: true
  44518. });
  44519. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  44520. /**
  44521. * Gets the vertical size of the blur.
  44522. */
  44523. get: function () {
  44524. return this._verticalBlurPostprocess.blurWidth;
  44525. },
  44526. /**
  44527. * Specifies the vertical size of the blur.
  44528. */
  44529. set: function (value) {
  44530. this._verticalBlurPostprocess.blurWidth = value;
  44531. },
  44532. enumerable: true,
  44533. configurable: true
  44534. });
  44535. Object.defineProperty(HighlightLayer.prototype, "camera", {
  44536. /**
  44537. * Gets the camera attached to the layer.
  44538. */
  44539. get: function () {
  44540. return this._options.camera;
  44541. },
  44542. enumerable: true,
  44543. configurable: true
  44544. });
  44545. /**
  44546. * Creates the render target textures and post processes used in the highlight layer.
  44547. */
  44548. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  44549. var _this = this;
  44550. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  44551. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  44552. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  44553. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  44554. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  44555. width: this._mainTextureDesiredSize.width,
  44556. height: this._mainTextureDesiredSize.height
  44557. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  44558. this._mainTexture.activeCamera = this._options.camera;
  44559. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44560. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44561. this._mainTexture.anisotropicFilteringLevel = 1;
  44562. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44563. this._mainTexture.renderParticles = false;
  44564. this._mainTexture.renderList = null;
  44565. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  44566. width: blurTextureWidth,
  44567. height: blurTextureHeight
  44568. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  44569. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44570. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44571. this._blurTexture.anisotropicFilteringLevel = 16;
  44572. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  44573. this._blurTexture.renderParticles = false;
  44574. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  44575. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  44576. effect.setTexture("textureSampler", _this._mainTexture);
  44577. });
  44578. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  44579. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  44580. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  44581. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  44582. });
  44583. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  44584. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  44585. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  44586. });
  44587. }
  44588. else {
  44589. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  44590. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  44591. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  44592. });
  44593. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  44594. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  44595. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  44596. });
  44597. }
  44598. this._mainTexture.onAfterUnbindObservable.add(function () {
  44599. _this.onBeforeBlurObservable.notifyObservers(_this);
  44600. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  44601. _this.onAfterBlurObservable.notifyObservers(_this);
  44602. });
  44603. // Custom render function
  44604. var renderSubMesh = function (subMesh) {
  44605. var mesh = subMesh.getRenderingMesh();
  44606. var scene = _this._scene;
  44607. var engine = scene.getEngine();
  44608. // Culling
  44609. engine.setState(subMesh.getMaterial().backFaceCulling);
  44610. // Managing instances
  44611. var batch = mesh._getInstancesRenderList(subMesh._id);
  44612. if (batch.mustReturn) {
  44613. return;
  44614. }
  44615. // Excluded Mesh
  44616. if (_this._excludedMeshes[mesh.uniqueId]) {
  44617. return;
  44618. }
  44619. ;
  44620. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  44621. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  44622. var material = subMesh.getMaterial();
  44623. var emissiveTexture = null;
  44624. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  44625. emissiveTexture = material.emissiveTexture;
  44626. }
  44627. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  44628. engine.enableEffect(_this._glowMapGenerationEffect);
  44629. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  44630. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  44631. if (highlightLayerMesh) {
  44632. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  44633. }
  44634. else {
  44635. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  44636. }
  44637. // Alpha test
  44638. if (material && material.needAlphaTesting()) {
  44639. var alphaTexture = material.getAlphaTestTexture();
  44640. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  44641. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  44642. }
  44643. // Glow emissive only
  44644. if (emissiveTexture) {
  44645. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  44646. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  44647. }
  44648. // Bones
  44649. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44650. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44651. }
  44652. // Draw
  44653. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  44654. }
  44655. else {
  44656. // Need to reset refresh rate of the shadowMap
  44657. _this._mainTexture.resetRefreshCounter();
  44658. }
  44659. };
  44660. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  44661. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  44662. var index;
  44663. for (index = 0; index < opaqueSubMeshes.length; index++) {
  44664. renderSubMesh(opaqueSubMeshes.data[index]);
  44665. }
  44666. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  44667. renderSubMesh(alphaTestSubMeshes.data[index]);
  44668. }
  44669. for (index = 0; index < transparentSubMeshes.length; index++) {
  44670. renderSubMesh(transparentSubMeshes.data[index]);
  44671. }
  44672. };
  44673. this._mainTexture.onClearObservable.add(function (engine) {
  44674. engine.clear(HighlightLayer.neutralColor, true, true, true);
  44675. });
  44676. };
  44677. /**
  44678. * Checks for the readiness of the element composing the layer.
  44679. * @param subMesh the mesh to check for
  44680. * @param useInstances specify wether or not to use instances to render the mesh
  44681. * @param emissiveTexture the associated emissive texture used to generate the glow
  44682. * @return true if ready otherwise, false
  44683. */
  44684. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  44685. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  44686. return false;
  44687. }
  44688. var defines = [];
  44689. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44690. var mesh = subMesh.getMesh();
  44691. var material = subMesh.getMaterial();
  44692. var uv1 = false;
  44693. var uv2 = false;
  44694. // Alpha test
  44695. if (material && material.needAlphaTesting()) {
  44696. var alphaTexture = material.getAlphaTestTexture();
  44697. if (alphaTexture) {
  44698. defines.push("#define ALPHATEST");
  44699. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  44700. alphaTexture.coordinatesIndex === 1) {
  44701. defines.push("#define DIFFUSEUV2");
  44702. uv2 = true;
  44703. }
  44704. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44705. defines.push("#define DIFFUSEUV1");
  44706. uv1 = true;
  44707. }
  44708. }
  44709. }
  44710. // Emissive
  44711. if (emissiveTexture) {
  44712. defines.push("#define EMISSIVE");
  44713. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  44714. emissiveTexture.coordinatesIndex === 1) {
  44715. defines.push("#define EMISSIVEUV2");
  44716. uv2 = true;
  44717. }
  44718. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44719. defines.push("#define EMISSIVEUV1");
  44720. uv1 = true;
  44721. }
  44722. }
  44723. if (uv1) {
  44724. attribs.push(BABYLON.VertexBuffer.UVKind);
  44725. defines.push("#define UV1");
  44726. }
  44727. if (uv2) {
  44728. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44729. defines.push("#define UV2");
  44730. }
  44731. // Bones
  44732. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44733. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  44734. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  44735. if (mesh.numBoneInfluencers > 4) {
  44736. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  44737. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  44738. }
  44739. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44740. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44741. }
  44742. else {
  44743. defines.push("#define NUM_BONE_INFLUENCERS 0");
  44744. }
  44745. // Instances
  44746. if (useInstances) {
  44747. defines.push("#define INSTANCES");
  44748. attribs.push("world0");
  44749. attribs.push("world1");
  44750. attribs.push("world2");
  44751. attribs.push("world3");
  44752. }
  44753. // Get correct effect
  44754. var join = defines.join("\n");
  44755. if (this._cachedDefines !== join) {
  44756. this._cachedDefines = join;
  44757. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  44758. }
  44759. return this._glowMapGenerationEffect.isReady();
  44760. };
  44761. /**
  44762. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  44763. */
  44764. HighlightLayer.prototype.render = function () {
  44765. var currentEffect = this._glowMapMergeEffect;
  44766. // Check
  44767. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  44768. return;
  44769. var engine = this._scene.getEngine();
  44770. this.onBeforeComposeObservable.notifyObservers(this);
  44771. // Render
  44772. engine.enableEffect(currentEffect);
  44773. engine.setState(false);
  44774. // Cache
  44775. var previousStencilBuffer = engine.getStencilBuffer();
  44776. var previousStencilFunction = engine.getStencilFunction();
  44777. var previousStencilMask = engine.getStencilMask();
  44778. var previousAlphaMode = engine.getAlphaMode();
  44779. // Texture
  44780. currentEffect.setTexture("textureSampler", this._blurTexture);
  44781. // VBOs
  44782. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  44783. // Draw order
  44784. engine.setAlphaMode(this._options.alphaBlendingMode);
  44785. engine.setStencilMask(0x00);
  44786. engine.setStencilBuffer(true);
  44787. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  44788. if (this.outerGlow) {
  44789. currentEffect.setFloat("offset", 0);
  44790. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  44791. engine.draw(true, 0, 6);
  44792. }
  44793. if (this.innerGlow) {
  44794. currentEffect.setFloat("offset", 1);
  44795. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  44796. engine.draw(true, 0, 6);
  44797. }
  44798. // Restore Cache
  44799. engine.setStencilFunction(previousStencilFunction);
  44800. engine.setStencilMask(previousStencilMask);
  44801. engine.setAlphaMode(previousAlphaMode);
  44802. engine.setStencilBuffer(previousStencilBuffer);
  44803. this.onAfterComposeObservable.notifyObservers(this);
  44804. // Handle size changes.
  44805. var size = this._mainTexture.getSize();
  44806. this.setMainTextureSize();
  44807. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  44808. // Recreate RTT and post processes on size change.
  44809. this.onSizeChangedObservable.notifyObservers(this);
  44810. this.disposeTextureAndPostProcesses();
  44811. this.createTextureAndPostProcesses();
  44812. }
  44813. };
  44814. /**
  44815. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  44816. * @param mesh The mesh to exclude from the highlight layer
  44817. */
  44818. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  44819. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  44820. if (!meshExcluded) {
  44821. this._excludedMeshes[mesh.uniqueId] = {
  44822. mesh: mesh,
  44823. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  44824. mesh.getEngine().setStencilBuffer(false);
  44825. }),
  44826. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  44827. mesh.getEngine().setStencilBuffer(true);
  44828. }),
  44829. };
  44830. }
  44831. };
  44832. /**
  44833. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  44834. * @param mesh The mesh to highlight
  44835. */
  44836. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  44837. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  44838. if (meshExcluded) {
  44839. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  44840. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  44841. }
  44842. this._excludedMeshes[mesh.uniqueId] = undefined;
  44843. };
  44844. /**
  44845. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  44846. * @param mesh The mesh to highlight
  44847. * @param color The color of the highlight
  44848. * @param glowEmissiveOnly Extract the glow from the emissive texture
  44849. */
  44850. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  44851. var _this = this;
  44852. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  44853. var meshHighlight = this._meshes[mesh.uniqueId];
  44854. if (meshHighlight) {
  44855. meshHighlight.color = color;
  44856. }
  44857. else {
  44858. this._meshes[mesh.uniqueId] = {
  44859. mesh: mesh,
  44860. color: color,
  44861. // Lambda required for capture due to Observable this context
  44862. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  44863. if (_this._excludedMeshes[mesh.uniqueId]) {
  44864. _this.defaultStencilReference(mesh);
  44865. }
  44866. else {
  44867. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  44868. }
  44869. }),
  44870. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  44871. glowEmissiveOnly: glowEmissiveOnly
  44872. };
  44873. }
  44874. this._shouldRender = true;
  44875. };
  44876. /**
  44877. * Remove a mesh from the highlight layer in order to make it stop glowing.
  44878. * @param mesh The mesh to highlight
  44879. */
  44880. HighlightLayer.prototype.removeMesh = function (mesh) {
  44881. var meshHighlight = this._meshes[mesh.uniqueId];
  44882. if (meshHighlight) {
  44883. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  44884. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  44885. }
  44886. this._meshes[mesh.uniqueId] = undefined;
  44887. this._shouldRender = false;
  44888. for (var meshHighlightToCheck in this._meshes) {
  44889. if (meshHighlightToCheck) {
  44890. this._shouldRender = true;
  44891. break;
  44892. }
  44893. }
  44894. };
  44895. /**
  44896. * Returns true if the layer contains information to display, otherwise false.
  44897. */
  44898. HighlightLayer.prototype.shouldRender = function () {
  44899. return this.isEnabled && this._shouldRender;
  44900. };
  44901. /**
  44902. * Sets the main texture desired size which is the closest power of two
  44903. * of the engine canvas size.
  44904. */
  44905. HighlightLayer.prototype.setMainTextureSize = function () {
  44906. if (this._options.mainTextureFixedSize) {
  44907. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  44908. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  44909. }
  44910. else {
  44911. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  44912. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  44913. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  44914. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  44915. }
  44916. };
  44917. /**
  44918. * Force the stencil to the normal expected value for none glowing parts
  44919. */
  44920. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  44921. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  44922. };
  44923. /**
  44924. * Dispose only the render target textures and post process.
  44925. */
  44926. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  44927. this._blurTexture.dispose();
  44928. this._mainTexture.dispose();
  44929. this._downSamplePostprocess.dispose();
  44930. this._horizontalBlurPostprocess.dispose();
  44931. this._verticalBlurPostprocess.dispose();
  44932. };
  44933. /**
  44934. * Dispose the highlight layer and free resources.
  44935. */
  44936. HighlightLayer.prototype.dispose = function () {
  44937. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  44938. if (vertexBuffer) {
  44939. vertexBuffer.dispose();
  44940. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  44941. }
  44942. if (this._indexBuffer) {
  44943. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44944. this._indexBuffer = null;
  44945. }
  44946. // Clean textures and post processes
  44947. this.disposeTextureAndPostProcesses();
  44948. // Clean mesh references
  44949. for (var id in this._meshes) {
  44950. var meshHighlight = this._meshes[id];
  44951. if (meshHighlight && meshHighlight.mesh) {
  44952. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  44953. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  44954. }
  44955. }
  44956. this._meshes = null;
  44957. for (var id in this._excludedMeshes) {
  44958. var meshHighlight = this._excludedMeshes[id];
  44959. if (meshHighlight) {
  44960. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  44961. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  44962. }
  44963. }
  44964. this._excludedMeshes = null;
  44965. // Remove from scene
  44966. var index = this._scene.highlightLayers.indexOf(this, 0);
  44967. if (index > -1) {
  44968. this._scene.highlightLayers.splice(index, 1);
  44969. }
  44970. // Callback
  44971. this.onDisposeObservable.notifyObservers(this);
  44972. this.onDisposeObservable.clear();
  44973. this.onBeforeRenderMainTextureObservable.clear();
  44974. this.onBeforeBlurObservable.clear();
  44975. this.onBeforeComposeObservable.clear();
  44976. this.onAfterComposeObservable.clear();
  44977. this.onSizeChangedObservable.clear();
  44978. };
  44979. return HighlightLayer;
  44980. }());
  44981. /**
  44982. * The neutral color used during the preparation of the glow effect.
  44983. * This is black by default as the blend operation is a blend operation.
  44984. */
  44985. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  44986. /**
  44987. * Stencil value used for glowing meshes.
  44988. */
  44989. HighlightLayer.glowingMeshStencilReference = 0x02;
  44990. /**
  44991. * Stencil value used for the other meshes in the scene.
  44992. */
  44993. HighlightLayer.normalMeshStencilReference = 0x01;
  44994. BABYLON.HighlightLayer = HighlightLayer;
  44995. })(BABYLON || (BABYLON = {}));
  44996. //# sourceMappingURL=babylon.highlightlayer.js.map
  44997. var BABYLON;
  44998. (function (BABYLON) {
  44999. var SIMDVector3 = (function () {
  45000. function SIMDVector3() {
  45001. }
  45002. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  45003. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  45004. };
  45005. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  45006. var m = transformation.m;
  45007. var m0 = SIMD.Float32x4.load(m, 0);
  45008. var m1 = SIMD.Float32x4.load(m, 4);
  45009. var m2 = SIMD.Float32x4.load(m, 8);
  45010. var m3 = SIMD.Float32x4.load(m, 12);
  45011. 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));
  45012. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  45013. result.x = SIMD.Float32x4.extractLane(r, 0);
  45014. result.y = SIMD.Float32x4.extractLane(r, 1);
  45015. result.z = SIMD.Float32x4.extractLane(r, 2);
  45016. };
  45017. return SIMDVector3;
  45018. }());
  45019. var SIMDMatrix = (function () {
  45020. function SIMDMatrix() {
  45021. }
  45022. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  45023. var tm = this.m;
  45024. var om = other.m;
  45025. var m0 = SIMD.Float32x4.load(om, 0);
  45026. var m1 = SIMD.Float32x4.load(om, 4);
  45027. var m2 = SIMD.Float32x4.load(om, 8);
  45028. var m3 = SIMD.Float32x4.load(om, 12);
  45029. for (var i = 0; i < 16; i += 4) {
  45030. 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)))));
  45031. }
  45032. return this;
  45033. };
  45034. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  45035. var src = this.m;
  45036. var dest = other.m;
  45037. // Load the 4 rows
  45038. var src0 = SIMD.Float32x4.load(src, 0);
  45039. var src1 = SIMD.Float32x4.load(src, 4);
  45040. var src2 = SIMD.Float32x4.load(src, 8);
  45041. var src3 = SIMD.Float32x4.load(src, 12);
  45042. // Transpose the source matrix. Sort of. Not a true transpose operation
  45043. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  45044. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  45045. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  45046. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  45047. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  45048. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  45049. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  45050. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  45051. // This is a true transposition, but it will lead to an incorrect result
  45052. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  45053. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  45054. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  45055. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  45056. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  45057. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  45058. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  45059. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  45060. // ----
  45061. tmp1 = SIMD.Float32x4.mul(row2, row3);
  45062. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  45063. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  45064. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  45065. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  45066. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  45067. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  45068. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  45069. // ----
  45070. tmp1 = SIMD.Float32x4.mul(row1, row2);
  45071. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  45072. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  45073. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  45074. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  45075. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  45076. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  45077. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  45078. // ----
  45079. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  45080. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  45081. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  45082. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  45083. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  45084. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  45085. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  45086. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  45087. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  45088. // ----
  45089. tmp1 = SIMD.Float32x4.mul(row0, row1);
  45090. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  45091. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  45092. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  45093. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  45094. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  45095. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  45096. // ----
  45097. tmp1 = SIMD.Float32x4.mul(row0, row3);
  45098. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  45099. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  45100. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  45101. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  45102. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  45103. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  45104. // ----
  45105. tmp1 = SIMD.Float32x4.mul(row0, row2);
  45106. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  45107. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  45108. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  45109. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  45110. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  45111. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  45112. // Compute determinant
  45113. var det = SIMD.Float32x4.mul(row0, minor0);
  45114. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  45115. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  45116. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  45117. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  45118. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  45119. // These shuffles aren't necessary if the faulty transposition is done
  45120. // up at the top of this function.
  45121. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  45122. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  45123. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  45124. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  45125. // Compute final values by multiplying with 1/det
  45126. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  45127. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  45128. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  45129. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  45130. return this;
  45131. };
  45132. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  45133. var out = result.m;
  45134. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  45135. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  45136. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  45137. // cc.kmVec3Subtract(f, pCenter, pEye);
  45138. var f = SIMD.Float32x4.sub(center, eye);
  45139. // cc.kmVec3Normalize(f, f);
  45140. var tmp = SIMD.Float32x4.mul(f, f);
  45141. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  45142. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  45143. // cc.kmVec3Assign(up, pUp);
  45144. // cc.kmVec3Normalize(up, up);
  45145. tmp = SIMD.Float32x4.mul(up, up);
  45146. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  45147. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  45148. // cc.kmVec3Cross(s, f, up);
  45149. 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)));
  45150. // cc.kmVec3Normalize(s, s);
  45151. tmp = SIMD.Float32x4.mul(s, s);
  45152. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  45153. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  45154. // cc.kmVec3Cross(u, s, f);
  45155. 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)));
  45156. // cc.kmVec3Normalize(s, s);
  45157. tmp = SIMD.Float32x4.mul(s, s);
  45158. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  45159. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  45160. var zero = SIMD.Float32x4.splat(0.0);
  45161. s = SIMD.Float32x4.neg(s);
  45162. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  45163. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  45164. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  45165. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  45166. 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);
  45167. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  45168. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  45169. 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)))));
  45170. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  45171. 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)))));
  45172. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  45173. 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)))));
  45174. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  45175. 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)))));
  45176. };
  45177. return SIMDMatrix;
  45178. }());
  45179. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  45180. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  45181. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  45182. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  45183. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  45184. var SIMDHelper = (function () {
  45185. function SIMDHelper() {
  45186. }
  45187. Object.defineProperty(SIMDHelper, "IsEnabled", {
  45188. get: function () {
  45189. return SIMDHelper._isEnabled;
  45190. },
  45191. enumerable: true,
  45192. configurable: true
  45193. });
  45194. SIMDHelper.DisableSIMD = function () {
  45195. // Replace functions
  45196. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  45197. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  45198. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  45199. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  45200. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  45201. SIMDHelper._isEnabled = false;
  45202. };
  45203. SIMDHelper.EnableSIMD = function () {
  45204. if (self.SIMD === undefined) {
  45205. return;
  45206. }
  45207. // check if polyfills needed
  45208. if (!self.Math.fround) {
  45209. self.Math.fround = (function (array) { return function (x) {
  45210. return array[0] = x, array[0];
  45211. }; })(new Float32Array(1));
  45212. }
  45213. if (!self.Math.imul) {
  45214. self.Math.imul = function (a, b) {
  45215. var ah = (a >>> 16) & 0xffff;
  45216. var al = a & 0xffff;
  45217. var bh = (b >>> 16) & 0xffff;
  45218. var bl = b & 0xffff;
  45219. // the shift by 0 fixes the sign on the high part
  45220. // the final |0 converts the unsigned value into a signed value
  45221. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  45222. };
  45223. }
  45224. // Replace functions
  45225. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  45226. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  45227. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  45228. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  45229. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  45230. SIMDHelper._isEnabled = true;
  45231. };
  45232. return SIMDHelper;
  45233. }());
  45234. SIMDHelper._isEnabled = false;
  45235. BABYLON.SIMDHelper = SIMDHelper;
  45236. })(BABYLON || (BABYLON = {}));
  45237. //# sourceMappingURL=babylon.math.SIMD.js.map
  45238. var BABYLON;
  45239. (function (BABYLON) {
  45240. /**
  45241. * This class describe a rectangle that were added to the map.
  45242. * You have access to its coordinates either in pixel or normalized (UV)
  45243. */
  45244. var PackedRect = (function () {
  45245. function PackedRect(root, parent, pos, size) {
  45246. this._pos = pos;
  45247. this._size = size;
  45248. this._root = root;
  45249. this._parent = parent;
  45250. this._contentSize = null;
  45251. this._bottomNode = null;
  45252. this._leftNode = null;
  45253. this._initialSize = null;
  45254. this._rightNode = null;
  45255. }
  45256. Object.defineProperty(PackedRect.prototype, "pos", {
  45257. /**
  45258. * @returns the position of this node into the map
  45259. */
  45260. get: function () {
  45261. return this._pos;
  45262. },
  45263. enumerable: true,
  45264. configurable: true
  45265. });
  45266. Object.defineProperty(PackedRect.prototype, "contentSize", {
  45267. /**
  45268. * @returns the size of the rectangle this node handles
  45269. */
  45270. get: function () {
  45271. return this._contentSize;
  45272. },
  45273. enumerable: true,
  45274. configurable: true
  45275. });
  45276. /**
  45277. * Retrieve the inner position (considering the margin) and stores it into the res object
  45278. * @param res must be a valid Vector2 that will contain the inner position after this call
  45279. */
  45280. PackedRect.prototype.getInnerPosToRef = function (res) {
  45281. var m = this._root._margin;
  45282. res.x = this._pos.x + m;
  45283. res.y = this._pos.y + m;
  45284. };
  45285. /**
  45286. * Retrieve the inner size (considering the margin) and stores it into the res object
  45287. * @param res must be a valid Size that will contain the inner size after this call
  45288. */
  45289. PackedRect.prototype.getInnerSizeToRef = function (res) {
  45290. var m = this._root._margin;
  45291. res.width = this._contentSize.width - (m * 2);
  45292. res.height = this._contentSize.height - (m * 2);
  45293. };
  45294. Object.defineProperty(PackedRect.prototype, "UVs", {
  45295. /**
  45296. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  45297. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  45298. */
  45299. get: function () {
  45300. if (!this._contentSize) {
  45301. throw new Error("Can't compute UVs for this object because it's nor allocated");
  45302. }
  45303. return this.getUVsForCustomSize(this._contentSize);
  45304. },
  45305. enumerable: true,
  45306. configurable: true
  45307. });
  45308. /**
  45309. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  45310. * and then using only a part of the PackRect.
  45311. * This method will return the UVs for this part by given the custom size of what you really use
  45312. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  45313. */
  45314. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  45315. var mainWidth = this._root._size.width;
  45316. var mainHeight = this._root._size.height;
  45317. var margin = this._root._margin;
  45318. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  45319. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  45320. var uvs = new Array();
  45321. uvs.push(topLeft);
  45322. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  45323. uvs.push(rightBottom);
  45324. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  45325. return uvs;
  45326. };
  45327. /**
  45328. * Free this rectangle from the map.
  45329. * Call this method when you no longer need the rectangle to be in the map.
  45330. */
  45331. PackedRect.prototype.freeContent = function () {
  45332. if (!this.contentSize) {
  45333. return;
  45334. }
  45335. this._contentSize = null;
  45336. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  45337. this.attemptDefrag();
  45338. };
  45339. Object.defineProperty(PackedRect.prototype, "isUsed", {
  45340. get: function () {
  45341. return this._contentSize != null || this._leftNode != null;
  45342. },
  45343. enumerable: true,
  45344. configurable: true
  45345. });
  45346. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  45347. var node = this.findNode(contentSize);
  45348. // Not enough space...
  45349. if (!node) {
  45350. return null;
  45351. }
  45352. node.splitNode(contentSize);
  45353. return node;
  45354. };
  45355. PackedRect.prototype.findNode = function (size) {
  45356. var resNode = null;
  45357. var margin = this._root._margin * 2;
  45358. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  45359. if (this.isUsed) {
  45360. if (this._leftNode) {
  45361. resNode = this._leftNode.findNode(size);
  45362. }
  45363. if (!resNode && this._rightNode) {
  45364. resNode = this._rightNode.findNode(size);
  45365. }
  45366. if (!resNode && this._bottomNode) {
  45367. resNode = this._bottomNode.findNode(size);
  45368. }
  45369. }
  45370. else if (this._initialSize) {
  45371. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  45372. resNode = this;
  45373. }
  45374. else {
  45375. return null;
  45376. }
  45377. }
  45378. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  45379. resNode = this;
  45380. }
  45381. return resNode;
  45382. };
  45383. PackedRect.prototype.splitNode = function (contentSize) {
  45384. var cs = PackedRect.TpsSize;
  45385. var margin = this._root._margin * 2;
  45386. cs.copyFrom(contentSize);
  45387. cs.width += margin;
  45388. cs.height += margin;
  45389. // 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)
  45390. if (!this._contentSize && this._initialSize) {
  45391. this._contentSize = cs.clone();
  45392. 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));
  45393. return this._leftNode.splitNode(contentSize);
  45394. }
  45395. else {
  45396. this._contentSize = cs.clone();
  45397. this._initialSize = cs.clone();
  45398. if (cs.width !== this._size.width) {
  45399. 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));
  45400. }
  45401. if (cs.height !== this._size.height) {
  45402. 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));
  45403. }
  45404. return this;
  45405. }
  45406. };
  45407. PackedRect.prototype.attemptDefrag = function () {
  45408. if (!this.isUsed && this.isRecursiveFree) {
  45409. this.clearNode();
  45410. if (this._parent) {
  45411. this._parent.attemptDefrag();
  45412. }
  45413. }
  45414. };
  45415. PackedRect.prototype.clearNode = function () {
  45416. this._initialSize = null;
  45417. this._rightNode = null;
  45418. this._bottomNode = null;
  45419. };
  45420. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  45421. get: function () {
  45422. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  45423. },
  45424. enumerable: true,
  45425. configurable: true
  45426. });
  45427. PackedRect.prototype.evalFreeSize = function (size) {
  45428. var levelSize = 0;
  45429. if (!this.isUsed) {
  45430. var margin = this._root._margin;
  45431. var is = this._initialSize;
  45432. if (is) {
  45433. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  45434. }
  45435. else {
  45436. var size_1 = this._size;
  45437. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  45438. }
  45439. }
  45440. if (this._rightNode) {
  45441. levelSize += this._rightNode.evalFreeSize(0);
  45442. }
  45443. if (this._bottomNode) {
  45444. levelSize += this._bottomNode.evalFreeSize(0);
  45445. }
  45446. return levelSize + size;
  45447. };
  45448. return PackedRect;
  45449. }());
  45450. PackedRect.TpsSize = BABYLON.Size.Zero();
  45451. BABYLON.PackedRect = PackedRect;
  45452. /**
  45453. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  45454. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  45455. * 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.
  45456. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  45457. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  45458. */
  45459. var RectPackingMap = (function (_super) {
  45460. __extends(RectPackingMap, _super);
  45461. /**
  45462. * Create an instance of the object with a dimension using the given size
  45463. * @param size The dimension of the rectangle that will contain all the sub ones.
  45464. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  45465. */
  45466. function RectPackingMap(size, margin) {
  45467. if (margin === void 0) { margin = 0; }
  45468. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  45469. _this._margin = margin;
  45470. _this._root = _this;
  45471. return _this;
  45472. }
  45473. /**
  45474. * Add a rectangle, finding the best location to store it into the map
  45475. * @param size the dimension of the rectangle to store
  45476. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  45477. */
  45478. RectPackingMap.prototype.addRect = function (size) {
  45479. var node = this.findAndSplitNode(size);
  45480. return node;
  45481. };
  45482. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  45483. /**
  45484. * Return the current space free normalized between [0;1]
  45485. * @returns {}
  45486. */
  45487. get: function () {
  45488. var freeSize = 0;
  45489. freeSize = this.evalFreeSize(freeSize);
  45490. return freeSize / (this._size.width * this._size.height);
  45491. },
  45492. enumerable: true,
  45493. configurable: true
  45494. });
  45495. return RectPackingMap;
  45496. }(PackedRect));
  45497. BABYLON.RectPackingMap = RectPackingMap;
  45498. })(BABYLON || (BABYLON = {}));
  45499. //# sourceMappingURL=babylon.rectPackingMap.js.map
  45500. var BABYLON;
  45501. (function (BABYLON) {
  45502. var DynamicFloatArrayElementInfo = (function () {
  45503. function DynamicFloatArrayElementInfo() {
  45504. }
  45505. return DynamicFloatArrayElementInfo;
  45506. }());
  45507. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  45508. /**
  45509. * 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.
  45510. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  45511. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  45512. * 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.
  45513. * 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.
  45514. * 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".
  45515. */
  45516. var DynamicFloatArray = (function () {
  45517. /**
  45518. * Construct an instance of the dynamic float array
  45519. * @param stride size of one element in float (i.e. not bytes!)
  45520. * @param initialElementCount the number of available entries at construction
  45521. */
  45522. function DynamicFloatArray(stride, initialElementCount) {
  45523. this.compareValueOffset = null;
  45524. this.sortingAscending = true;
  45525. this._stride = stride;
  45526. this.buffer = new Float32Array(stride * initialElementCount);
  45527. this._lastUsed = 0;
  45528. this._firstFree = 0;
  45529. this._allEntries = new Array(initialElementCount);
  45530. this._freeEntries = new Array(initialElementCount);
  45531. for (var i = 0; i < initialElementCount; i++) {
  45532. var element = new DynamicFloatArrayElementInfo();
  45533. element.offset = i * stride;
  45534. this._allEntries[i] = element;
  45535. this._freeEntries[initialElementCount - i - 1] = element;
  45536. }
  45537. }
  45538. /**
  45539. * Allocate an element in the array.
  45540. * @return the element info instance that contains the offset into the main buffer of the element's location.
  45541. * Beware, this offset may change when you call pack()
  45542. */
  45543. DynamicFloatArray.prototype.allocElement = function () {
  45544. if (this._freeEntries.length === 0) {
  45545. this._growBuffer();
  45546. }
  45547. var el = this._freeEntries.pop();
  45548. this._lastUsed = Math.max(el.offset, this._lastUsed);
  45549. if (el.offset === this._firstFree) {
  45550. if (this._freeEntries.length > 0) {
  45551. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  45552. }
  45553. else {
  45554. this._firstFree += this._stride;
  45555. }
  45556. }
  45557. return el;
  45558. };
  45559. /**
  45560. * Free the element corresponding to the given element info
  45561. * @param elInfo the element that describe the allocated element
  45562. */
  45563. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  45564. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  45565. this._freeEntries.push(elInfo);
  45566. };
  45567. /**
  45568. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  45569. * 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().
  45570. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  45571. */
  45572. DynamicFloatArray.prototype.pack = function () {
  45573. // no free slot? no need to pack
  45574. if (this._freeEntries.length === 0) {
  45575. return this.buffer;
  45576. }
  45577. // If the buffer is already packed the last used will always be lower than the first free
  45578. // 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.
  45579. if (this._lastUsed < this._firstFree) {
  45580. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  45581. return elementsBuffer_1;
  45582. }
  45583. var s = this._stride;
  45584. // 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
  45585. var lastFree = new DynamicFloatArrayElementInfo();
  45586. lastFree.offset = this.totalElementCount * s;
  45587. this._freeEntries.push(lastFree);
  45588. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  45589. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  45590. var firstFreeSlotOffset = sortedFree[0].offset;
  45591. var freeZoneSize = 1;
  45592. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  45593. var prevOffset = sortedFree[0].offset;
  45594. for (var i = 1; i < sortedFree.length; i++) {
  45595. // 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
  45596. if (firstFreeSlotOffset >= occupiedZoneSize) {
  45597. break;
  45598. }
  45599. var curFree = sortedFree[i];
  45600. var curOffset = curFree.offset;
  45601. // Compute the distance between this offset and the previous
  45602. var distance = curOffset - prevOffset;
  45603. // If the distance is the stride size, they are adjacent, it good, move to the next
  45604. if (distance === s) {
  45605. // Free zone is one element bigger
  45606. ++freeZoneSize;
  45607. // as we're about to iterate to the next, the cur becomes the previous...
  45608. prevOffset = curOffset;
  45609. continue;
  45610. }
  45611. // Distance is bigger, which means there's x element between the previous free and this one
  45612. var usedRange = (distance / s) - 1;
  45613. // Two cases the free zone is smaller than the data to move or bigger
  45614. // Copy what can fit in the free zone
  45615. var curMoveOffset = curOffset - s;
  45616. var copyCount = Math.min(freeZoneSize, usedRange);
  45617. for (var j = 0; j < copyCount; j++) {
  45618. var freeI = firstFreeSlotOffset / s;
  45619. var curI = curMoveOffset / s;
  45620. var moveEl = sortedAll[curI];
  45621. this._moveElement(moveEl, firstFreeSlotOffset);
  45622. var replacedEl = sortedAll[freeI];
  45623. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  45624. replacedEl.offset = curMoveOffset;
  45625. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  45626. sortedAll[freeI] = moveEl;
  45627. sortedAll[curI] = replacedEl;
  45628. curMoveOffset -= s;
  45629. firstFreeSlotOffset += s;
  45630. }
  45631. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  45632. if (freeZoneSize <= usedRange) {
  45633. firstFreeSlotOffset = curMoveOffset + s;
  45634. freeZoneSize = 1 + copyCount;
  45635. }
  45636. else {
  45637. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  45638. }
  45639. // as we're about to iterate to the next, the cur becomes the previous...
  45640. prevOffset = curOffset;
  45641. }
  45642. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  45643. this._lastUsed = firstFreeSlotOffset - s;
  45644. this._firstFree = firstFreeSlotOffset;
  45645. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  45646. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  45647. this._allEntries = sortedAll;
  45648. return elementsBuffer;
  45649. };
  45650. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  45651. for (var i = 0; i < this._stride; i++) {
  45652. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  45653. }
  45654. element.offset = destOffset;
  45655. };
  45656. DynamicFloatArray.prototype._growBuffer = function () {
  45657. // Allocate the new buffer with 50% more entries, copy the content of the current one
  45658. var newElCount = Math.floor(this.totalElementCount * 1.5);
  45659. var newBuffer = new Float32Array(newElCount * this._stride);
  45660. newBuffer.set(this.buffer);
  45661. var curCount = this.totalElementCount;
  45662. var addedCount = newElCount - this.totalElementCount;
  45663. for (var i = 0; i < addedCount; i++) {
  45664. var element = new DynamicFloatArrayElementInfo();
  45665. element.offset = (curCount + i) * this.stride;
  45666. this._allEntries.push(element);
  45667. this._freeEntries[addedCount - i - 1] = element;
  45668. }
  45669. this._firstFree = curCount * this.stride;
  45670. this.buffer = newBuffer;
  45671. };
  45672. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  45673. /**
  45674. * Get the total count of entries that can fit in the current buffer
  45675. * @returns the elements count
  45676. */
  45677. get: function () {
  45678. return this._allEntries.length;
  45679. },
  45680. enumerable: true,
  45681. configurable: true
  45682. });
  45683. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  45684. /**
  45685. * Get the count of free entries that can still be allocated without resizing the buffer
  45686. * @returns the free elements count
  45687. */
  45688. get: function () {
  45689. return this._freeEntries.length;
  45690. },
  45691. enumerable: true,
  45692. configurable: true
  45693. });
  45694. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  45695. /**
  45696. * Get the count of allocated elements
  45697. * @returns the allocated elements count
  45698. */
  45699. get: function () {
  45700. return this._allEntries.length - this._freeEntries.length;
  45701. },
  45702. enumerable: true,
  45703. configurable: true
  45704. });
  45705. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  45706. /**
  45707. * Return the size of one element in float
  45708. * @returns the size in float
  45709. */
  45710. get: function () {
  45711. return this._stride;
  45712. },
  45713. enumerable: true,
  45714. configurable: true
  45715. });
  45716. DynamicFloatArray.prototype.sort = function () {
  45717. var _this = this;
  45718. if (!this.compareValueOffset) {
  45719. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  45720. }
  45721. var count = this.usedElementCount;
  45722. // Do we have to (re)create the sort table?
  45723. if (!this._sortTable || this._sortTable.length < count) {
  45724. // 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...
  45725. var newCount = Math.min(this.totalElementCount, count * 2);
  45726. this._sortTable = new Array(newCount);
  45727. }
  45728. if (!this._sortedTable || this._sortedTable.length !== count) {
  45729. this._sortedTable = new Array(count);
  45730. }
  45731. // Because, you know...
  45732. this.pack();
  45733. //let stride = this.stride;
  45734. //for (let i = 0; i < count; i++) {
  45735. // let si = this._sortTable[i];
  45736. // if (!si) {
  45737. // si = new SortInfo();
  45738. // this._sortTable[i] = si;
  45739. // }
  45740. // si.entry = this._allEntries[i];
  45741. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  45742. // si.swapedOffset = null;
  45743. // this._sortedTable[i] = si;
  45744. //}
  45745. var curOffset = 0;
  45746. var stride = this.stride;
  45747. for (var i = 0; i < count; i++, curOffset += stride) {
  45748. var si = this._sortTable[i];
  45749. if (!si) {
  45750. si = new SortInfo();
  45751. this._sortTable[i] = si;
  45752. }
  45753. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  45754. si.offset = curOffset;
  45755. si.swapedOffset = null;
  45756. this._sortedTable[i] = si;
  45757. }
  45758. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  45759. if (this.sortingAscending) {
  45760. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  45761. }
  45762. else {
  45763. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  45764. }
  45765. var swapElements = function (src, dst) {
  45766. for (var i = 0; i < stride; i++) {
  45767. var tps = _this.buffer[dst + i];
  45768. _this.buffer[dst + i] = _this.buffer[src + i];
  45769. _this.buffer[src + i] = tps;
  45770. }
  45771. };
  45772. // 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:
  45773. // 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),
  45774. // and I still want something with a good algorithm complexity.
  45775. // 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,
  45776. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  45777. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  45778. // 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
  45779. // until we find a SortInfo object without a swapedOffset which means we got the right location
  45780. // 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
  45781. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  45782. for (var i = 0; i < count; i++) {
  45783. // Get the element to move
  45784. var sourceSI = this._sortedTable[i];
  45785. var destSI = this._sortTable[i];
  45786. var sourceOff = sourceSI.offset;
  45787. // If the source changed location, find the new one
  45788. if (sourceSI.swapedOffset) {
  45789. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  45790. var curSI = sourceSI;
  45791. while (curSI.swapedOffset) {
  45792. curSI = this._sortTable[curSI.swapedOffset / stride];
  45793. }
  45794. // Finally get the right location
  45795. sourceOff = curSI.offset;
  45796. }
  45797. // Tag the element being replaced with its new location
  45798. destSI.swapedOffset = sourceOff;
  45799. // Swap elements (only if needed)
  45800. if (sourceOff !== destSI.offset) {
  45801. swapElements(sourceOff, destSI.offset);
  45802. }
  45803. // Update the offset in the corresponding DFAE
  45804. //sourceSI.entry.offset = destSI.entry.offset;
  45805. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  45806. }
  45807. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  45808. return true;
  45809. };
  45810. return DynamicFloatArray;
  45811. }());
  45812. BABYLON.DynamicFloatArray = DynamicFloatArray;
  45813. var SortInfo = (function () {
  45814. function SortInfo() {
  45815. this.compareData = this.offset = this.swapedOffset = null;
  45816. }
  45817. return SortInfo;
  45818. }());
  45819. })(BABYLON || (BABYLON = {}));
  45820. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  45821. var BABYLON;
  45822. (function (BABYLON) {
  45823. var MapTexture = (function (_super) {
  45824. __extends(MapTexture, _super);
  45825. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  45826. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45827. if (useMipMap === void 0) { useMipMap = false; }
  45828. if (margin === void 0) { margin = 0; }
  45829. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  45830. _this.name = name;
  45831. _this._size = size;
  45832. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45833. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45834. // Create the rectPackMap that will allocate portion of the texture
  45835. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  45836. // Create the texture that will store the content
  45837. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  45838. return _this;
  45839. }
  45840. /**
  45841. * Allocate a rectangle of a given size in the texture map
  45842. * @param size the size of the rectangle to allocation
  45843. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  45844. */
  45845. MapTexture.prototype.allocateRect = function (size) {
  45846. return this._rectPackingMap.addRect(size);
  45847. };
  45848. /**
  45849. * Free a given rectangle from the texture map
  45850. * @param rectInfo the instance corresponding to the rect to free.
  45851. */
  45852. MapTexture.prototype.freeRect = function (rectInfo) {
  45853. if (rectInfo) {
  45854. rectInfo.freeContent();
  45855. }
  45856. };
  45857. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  45858. /**
  45859. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  45860. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  45861. * @returns {}
  45862. */
  45863. get: function () {
  45864. return this._rectPackingMap.freeSpace;
  45865. },
  45866. enumerable: true,
  45867. configurable: true
  45868. });
  45869. /**
  45870. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  45871. * 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.
  45872. * Don't forget to call unbindTexture when you're done rendering
  45873. * @param rect the zone to render to
  45874. * @param clear true to clear the portion's color/depth data
  45875. */
  45876. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  45877. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  45878. };
  45879. /**
  45880. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  45881. * 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.
  45882. * Don't forget to call unbindTexture when you're done rendering
  45883. * @param pos the position into the texture
  45884. * @param size the portion to fit the clip space to
  45885. * @param clear true to clear the portion's color/depth data
  45886. */
  45887. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  45888. var engine = this.getScene().getEngine();
  45889. engine.bindFramebuffer(this._texture);
  45890. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  45891. if (clear) {
  45892. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  45893. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  45894. }
  45895. };
  45896. /**
  45897. * Unbind the texture map from the rendering engine.
  45898. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  45899. * @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.
  45900. */
  45901. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  45902. // Dump ?
  45903. if (dumpForDebug) {
  45904. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  45905. }
  45906. var engine = this.getScene().getEngine();
  45907. if (this._replacedViewport) {
  45908. engine.setViewport(this._replacedViewport);
  45909. this._replacedViewport = null;
  45910. }
  45911. engine.unBindFramebuffer(this._texture);
  45912. };
  45913. Object.defineProperty(MapTexture.prototype, "canRescale", {
  45914. get: function () {
  45915. return false;
  45916. },
  45917. enumerable: true,
  45918. configurable: true
  45919. });
  45920. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  45921. // Anyway, there's not much point to use this method for this kind of texture I guess
  45922. MapTexture.prototype.clone = function () {
  45923. return null;
  45924. };
  45925. return MapTexture;
  45926. }(BABYLON.Texture));
  45927. BABYLON.MapTexture = MapTexture;
  45928. })(BABYLON || (BABYLON = {}));
  45929. //# sourceMappingURL=babylon.mapTexture.js.map
  45930. var BABYLON;
  45931. (function (BABYLON) {
  45932. var ShaderMaterial = (function (_super) {
  45933. __extends(ShaderMaterial, _super);
  45934. function ShaderMaterial(name, scene, shaderPath, options) {
  45935. var _this = _super.call(this, name, scene) || this;
  45936. _this._textures = {};
  45937. _this._textureArrays = {};
  45938. _this._floats = {};
  45939. _this._floatsArrays = {};
  45940. _this._colors3 = {};
  45941. _this._colors4 = {};
  45942. _this._vectors2 = {};
  45943. _this._vectors3 = {};
  45944. _this._vectors4 = {};
  45945. _this._matrices = {};
  45946. _this._matrices3x3 = {};
  45947. _this._matrices2x2 = {};
  45948. _this._vectors3Arrays = {};
  45949. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  45950. _this._shaderPath = shaderPath;
  45951. options.needAlphaBlending = options.needAlphaBlending || false;
  45952. options.needAlphaTesting = options.needAlphaTesting || false;
  45953. options.attributes = options.attributes || ["position", "normal", "uv"];
  45954. options.uniforms = options.uniforms || ["worldViewProjection"];
  45955. options.samplers = options.samplers || [];
  45956. options.defines = options.defines || [];
  45957. _this._options = options;
  45958. return _this;
  45959. }
  45960. ShaderMaterial.prototype.getClassName = function () {
  45961. return "ShaderMaterial";
  45962. };
  45963. ShaderMaterial.prototype.needAlphaBlending = function () {
  45964. return this._options.needAlphaBlending;
  45965. };
  45966. ShaderMaterial.prototype.needAlphaTesting = function () {
  45967. return this._options.needAlphaTesting;
  45968. };
  45969. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  45970. if (this._options.uniforms.indexOf(uniformName) === -1) {
  45971. this._options.uniforms.push(uniformName);
  45972. }
  45973. };
  45974. ShaderMaterial.prototype.setTexture = function (name, texture) {
  45975. if (this._options.samplers.indexOf(name) === -1) {
  45976. this._options.samplers.push(name);
  45977. }
  45978. this._textures[name] = texture;
  45979. return this;
  45980. };
  45981. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  45982. if (this._options.samplers.indexOf(name) === -1) {
  45983. this._options.samplers.push(name);
  45984. }
  45985. this._checkUniform(name);
  45986. this._textureArrays[name] = textures;
  45987. return this;
  45988. };
  45989. ShaderMaterial.prototype.setFloat = function (name, value) {
  45990. this._checkUniform(name);
  45991. this._floats[name] = value;
  45992. return this;
  45993. };
  45994. ShaderMaterial.prototype.setFloats = function (name, value) {
  45995. this._checkUniform(name);
  45996. this._floatsArrays[name] = value;
  45997. return this;
  45998. };
  45999. ShaderMaterial.prototype.setColor3 = function (name, value) {
  46000. this._checkUniform(name);
  46001. this._colors3[name] = value;
  46002. return this;
  46003. };
  46004. ShaderMaterial.prototype.setColor4 = function (name, value) {
  46005. this._checkUniform(name);
  46006. this._colors4[name] = value;
  46007. return this;
  46008. };
  46009. ShaderMaterial.prototype.setVector2 = function (name, value) {
  46010. this._checkUniform(name);
  46011. this._vectors2[name] = value;
  46012. return this;
  46013. };
  46014. ShaderMaterial.prototype.setVector3 = function (name, value) {
  46015. this._checkUniform(name);
  46016. this._vectors3[name] = value;
  46017. return this;
  46018. };
  46019. ShaderMaterial.prototype.setVector4 = function (name, value) {
  46020. this._checkUniform(name);
  46021. this._vectors4[name] = value;
  46022. return this;
  46023. };
  46024. ShaderMaterial.prototype.setMatrix = function (name, value) {
  46025. this._checkUniform(name);
  46026. this._matrices[name] = value;
  46027. return this;
  46028. };
  46029. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  46030. this._checkUniform(name);
  46031. this._matrices3x3[name] = value;
  46032. return this;
  46033. };
  46034. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  46035. this._checkUniform(name);
  46036. this._matrices2x2[name] = value;
  46037. return this;
  46038. };
  46039. ShaderMaterial.prototype.setArray3 = function (name, value) {
  46040. this._checkUniform(name);
  46041. this._vectors3Arrays[name] = value;
  46042. return this;
  46043. };
  46044. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  46045. if (!mesh) {
  46046. return true;
  46047. }
  46048. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  46049. return false;
  46050. }
  46051. return false;
  46052. };
  46053. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  46054. var scene = this.getScene();
  46055. var engine = scene.getEngine();
  46056. if (!this.checkReadyOnEveryCall) {
  46057. if (this._renderId === scene.getRenderId()) {
  46058. if (this._checkCache(scene, mesh, useInstances)) {
  46059. return true;
  46060. }
  46061. }
  46062. }
  46063. // Instances
  46064. var defines = [];
  46065. var fallbacks = new BABYLON.EffectFallbacks();
  46066. if (useInstances) {
  46067. defines.push("#define INSTANCES");
  46068. }
  46069. for (var index = 0; index < this._options.defines.length; index++) {
  46070. defines.push(this._options.defines[index]);
  46071. }
  46072. // Bones
  46073. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  46074. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46075. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46076. fallbacks.addCPUSkinningFallback(0, mesh);
  46077. }
  46078. // Textures
  46079. for (var name in this._textures) {
  46080. if (!this._textures[name].isReady()) {
  46081. return false;
  46082. }
  46083. }
  46084. // Alpha test
  46085. if (engine.getAlphaTesting()) {
  46086. defines.push("#define ALPHATEST");
  46087. }
  46088. var previousEffect = this._effect;
  46089. var join = defines.join("\n");
  46090. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  46091. if (!this._effect.isReady()) {
  46092. return false;
  46093. }
  46094. if (previousEffect !== this._effect) {
  46095. scene.resetCachedMaterial();
  46096. }
  46097. this._renderId = scene.getRenderId();
  46098. return true;
  46099. };
  46100. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46101. var scene = this.getScene();
  46102. if (this._options.uniforms.indexOf("world") !== -1) {
  46103. this._effect.setMatrix("world", world);
  46104. }
  46105. if (this._options.uniforms.indexOf("worldView") !== -1) {
  46106. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  46107. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  46108. }
  46109. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  46110. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  46111. }
  46112. };
  46113. ShaderMaterial.prototype.bind = function (world, mesh) {
  46114. // Std values
  46115. this.bindOnlyWorldMatrix(world);
  46116. if (this.getScene().getCachedMaterial() !== this) {
  46117. if (this._options.uniforms.indexOf("view") !== -1) {
  46118. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  46119. }
  46120. if (this._options.uniforms.indexOf("projection") !== -1) {
  46121. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  46122. }
  46123. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  46124. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  46125. }
  46126. // Bones
  46127. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  46128. var name;
  46129. // Texture
  46130. for (name in this._textures) {
  46131. this._effect.setTexture(name, this._textures[name]);
  46132. }
  46133. // Texture arrays
  46134. for (name in this._textureArrays) {
  46135. this._effect.setTextureArray(name, this._textureArrays[name]);
  46136. }
  46137. // Float
  46138. for (name in this._floats) {
  46139. this._effect.setFloat(name, this._floats[name]);
  46140. }
  46141. // Float s
  46142. for (name in this._floatsArrays) {
  46143. this._effect.setArray(name, this._floatsArrays[name]);
  46144. }
  46145. // Color3
  46146. for (name in this._colors3) {
  46147. this._effect.setColor3(name, this._colors3[name]);
  46148. }
  46149. // Color4
  46150. for (name in this._colors4) {
  46151. var color = this._colors4[name];
  46152. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46153. }
  46154. // Vector2
  46155. for (name in this._vectors2) {
  46156. this._effect.setVector2(name, this._vectors2[name]);
  46157. }
  46158. // Vector3
  46159. for (name in this._vectors3) {
  46160. this._effect.setVector3(name, this._vectors3[name]);
  46161. }
  46162. // Vector4
  46163. for (name in this._vectors4) {
  46164. this._effect.setVector4(name, this._vectors4[name]);
  46165. }
  46166. // Matrix
  46167. for (name in this._matrices) {
  46168. this._effect.setMatrix(name, this._matrices[name]);
  46169. }
  46170. // Matrix 3x3
  46171. for (name in this._matrices3x3) {
  46172. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  46173. }
  46174. // Matrix 2x2
  46175. for (name in this._matrices2x2) {
  46176. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  46177. }
  46178. // Vector3Array
  46179. for (name in this._vectors3Arrays) {
  46180. this._effect.setArray3(name, this._vectors3Arrays[name]);
  46181. }
  46182. }
  46183. this._afterBind(mesh);
  46184. };
  46185. ShaderMaterial.prototype.clone = function (name) {
  46186. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  46187. return newShaderMaterial;
  46188. };
  46189. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46190. if (forceDisposeTextures) {
  46191. var name;
  46192. for (name in this._textures) {
  46193. this._textures[name].dispose();
  46194. }
  46195. for (name in this._textureArrays) {
  46196. var array = this._textureArrays[name];
  46197. for (var index = 0; index < array.length; index++) {
  46198. array[index].dispose();
  46199. }
  46200. }
  46201. }
  46202. this._textures = {};
  46203. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46204. };
  46205. ShaderMaterial.prototype.serialize = function () {
  46206. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46207. serializationObject.customType = "BABYLON.ShaderMaterial";
  46208. serializationObject.options = this._options;
  46209. serializationObject.shaderPath = this._shaderPath;
  46210. var name;
  46211. // Texture
  46212. serializationObject.textures = {};
  46213. for (name in this._textures) {
  46214. serializationObject.textures[name] = this._textures[name].serialize();
  46215. }
  46216. // Texture arrays
  46217. serializationObject.textureArrays = {};
  46218. for (name in this._textureArrays) {
  46219. serializationObject.textureArrays[name] = [];
  46220. var array = this._textureArrays[name];
  46221. for (var index = 0; index < array.length; index++) {
  46222. serializationObject.textureArrays[name].push(array[index].serialize());
  46223. }
  46224. }
  46225. // Float
  46226. serializationObject.floats = {};
  46227. for (name in this._floats) {
  46228. serializationObject.floats[name] = this._floats[name];
  46229. }
  46230. // Float s
  46231. serializationObject.floatArrays = {};
  46232. for (name in this._floatsArrays) {
  46233. serializationObject.floatArrays[name] = this._floatsArrays[name];
  46234. }
  46235. // Color3
  46236. serializationObject.colors3 = {};
  46237. for (name in this._colors3) {
  46238. serializationObject.colors3[name] = this._colors3[name].asArray();
  46239. }
  46240. // Color4
  46241. serializationObject.colors4 = {};
  46242. for (name in this._colors4) {
  46243. serializationObject.colors4[name] = this._colors4[name].asArray();
  46244. }
  46245. // Vector2
  46246. serializationObject.vectors2 = {};
  46247. for (name in this._vectors2) {
  46248. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  46249. }
  46250. // Vector3
  46251. serializationObject.vectors3 = {};
  46252. for (name in this._vectors3) {
  46253. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  46254. }
  46255. // Vector4
  46256. serializationObject.vectors4 = {};
  46257. for (name in this._vectors4) {
  46258. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  46259. }
  46260. // Matrix
  46261. serializationObject.matrices = {};
  46262. for (name in this._matrices) {
  46263. serializationObject.matrices[name] = this._matrices[name].asArray();
  46264. }
  46265. // Matrix 3x3
  46266. serializationObject.matrices3x3 = {};
  46267. for (name in this._matrices3x3) {
  46268. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  46269. }
  46270. // Matrix 2x2
  46271. serializationObject.matrices2x2 = {};
  46272. for (name in this._matrices2x2) {
  46273. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  46274. }
  46275. // Vector3Array
  46276. serializationObject.vectors3Arrays = {};
  46277. for (name in this._vectors3Arrays) {
  46278. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  46279. }
  46280. return serializationObject;
  46281. };
  46282. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  46283. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  46284. var name;
  46285. // Texture
  46286. for (name in source.textures) {
  46287. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  46288. }
  46289. // Texture arrays
  46290. for (name in source.textureArrays) {
  46291. var array = source.textureArrays[name];
  46292. var textureArray = new Array();
  46293. for (var index = 0; index < array.length; index++) {
  46294. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  46295. }
  46296. material.setTextureArray(name, textureArray);
  46297. }
  46298. // Float
  46299. for (name in source.floats) {
  46300. material.setFloat(name, source.floats[name]);
  46301. }
  46302. // Float s
  46303. for (name in source.floatsArrays) {
  46304. material.setFloats(name, source.floatsArrays[name]);
  46305. }
  46306. // Color3
  46307. for (name in source.colors3) {
  46308. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  46309. }
  46310. // Color4
  46311. for (name in source.colors4) {
  46312. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  46313. }
  46314. // Vector2
  46315. for (name in source.vectors2) {
  46316. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  46317. }
  46318. // Vector3
  46319. for (name in source.vectors3) {
  46320. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  46321. }
  46322. // Vector4
  46323. for (name in source.vectors4) {
  46324. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  46325. }
  46326. // Matrix
  46327. for (name in source.matrices) {
  46328. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  46329. }
  46330. // Matrix 3x3
  46331. for (name in source.matrices3x3) {
  46332. material.setMatrix3x3(name, source.matrices3x3[name]);
  46333. }
  46334. // Matrix 2x2
  46335. for (name in source.matrices2x2) {
  46336. material.setMatrix2x2(name, source.matrices2x2[name]);
  46337. }
  46338. // Vector3Array
  46339. for (name in source.vectors3Arrays) {
  46340. material.setArray3(name, source.vectors3Arrays[name]);
  46341. }
  46342. return material;
  46343. };
  46344. return ShaderMaterial;
  46345. }(BABYLON.Material));
  46346. BABYLON.ShaderMaterial = ShaderMaterial;
  46347. })(BABYLON || (BABYLON = {}));
  46348. //# sourceMappingURL=babylon.shaderMaterial.js.map
  46349. var BABYLON;
  46350. (function (BABYLON) {
  46351. var Internals;
  46352. (function (Internals) {
  46353. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  46354. // All values and structures referenced from:
  46355. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  46356. var DDS_MAGIC = 0x20534444;
  46357. 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;
  46358. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  46359. 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;
  46360. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  46361. function FourCCToInt32(value) {
  46362. return value.charCodeAt(0) +
  46363. (value.charCodeAt(1) << 8) +
  46364. (value.charCodeAt(2) << 16) +
  46365. (value.charCodeAt(3) << 24);
  46366. }
  46367. function Int32ToFourCC(value) {
  46368. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  46369. }
  46370. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  46371. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  46372. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  46373. var headerLengthInt = 31; // The header length in 32 bit ints
  46374. // Offsets into the header array
  46375. var off_magic = 0;
  46376. var off_size = 1;
  46377. var off_flags = 2;
  46378. var off_height = 3;
  46379. var off_width = 4;
  46380. var off_mipmapCount = 7;
  46381. var off_pfFlags = 20;
  46382. var off_pfFourCC = 21;
  46383. var off_RGBbpp = 22;
  46384. var off_RMask = 23;
  46385. var off_GMask = 24;
  46386. var off_BMask = 25;
  46387. var off_AMask = 26;
  46388. var off_caps1 = 27;
  46389. var off_caps2 = 28;
  46390. ;
  46391. var DDSTools = (function () {
  46392. function DDSTools() {
  46393. }
  46394. DDSTools.GetDDSInfo = function (arrayBuffer) {
  46395. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  46396. var mipmapCount = 1;
  46397. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  46398. mipmapCount = Math.max(1, header[off_mipmapCount]);
  46399. }
  46400. return {
  46401. width: header[off_width],
  46402. height: header[off_height],
  46403. mipmapCount: mipmapCount,
  46404. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  46405. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  46406. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  46407. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  46408. };
  46409. };
  46410. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  46411. var byteArray = new Uint8Array(dataLength);
  46412. var srcData = new Uint8Array(arrayBuffer);
  46413. var index = 0;
  46414. for (var y = height - 1; y >= 0; y--) {
  46415. for (var x = 0; x < width; x++) {
  46416. var srcPos = dataOffset + (x + y * width) * 4;
  46417. byteArray[index + 2] = srcData[srcPos];
  46418. byteArray[index + 1] = srcData[srcPos + 1];
  46419. byteArray[index] = srcData[srcPos + 2];
  46420. byteArray[index + 3] = srcData[srcPos + 3];
  46421. index += 4;
  46422. }
  46423. }
  46424. return byteArray;
  46425. };
  46426. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  46427. var byteArray = new Uint8Array(dataLength);
  46428. var srcData = new Uint8Array(arrayBuffer);
  46429. var index = 0;
  46430. for (var y = height - 1; y >= 0; y--) {
  46431. for (var x = 0; x < width; x++) {
  46432. var srcPos = dataOffset + (x + y * width) * 3;
  46433. byteArray[index + 2] = srcData[srcPos];
  46434. byteArray[index + 1] = srcData[srcPos + 1];
  46435. byteArray[index] = srcData[srcPos + 2];
  46436. index += 3;
  46437. }
  46438. }
  46439. return byteArray;
  46440. };
  46441. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  46442. var byteArray = new Uint8Array(dataLength);
  46443. var srcData = new Uint8Array(arrayBuffer);
  46444. var index = 0;
  46445. for (var y = height - 1; y >= 0; y--) {
  46446. for (var x = 0; x < width; x++) {
  46447. var srcPos = dataOffset + (x + y * width);
  46448. byteArray[index] = srcData[srcPos];
  46449. index++;
  46450. }
  46451. }
  46452. return byteArray;
  46453. };
  46454. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  46455. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  46456. if (header[off_magic] != DDS_MAGIC) {
  46457. BABYLON.Tools.Error("Invalid magic number in DDS header");
  46458. return;
  46459. }
  46460. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  46461. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  46462. return;
  46463. }
  46464. if (info.isFourCC) {
  46465. fourCC = header[off_pfFourCC];
  46466. switch (fourCC) {
  46467. case FOURCC_DXT1:
  46468. blockBytes = 8;
  46469. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  46470. break;
  46471. case FOURCC_DXT3:
  46472. blockBytes = 16;
  46473. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  46474. break;
  46475. case FOURCC_DXT5:
  46476. blockBytes = 16;
  46477. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  46478. break;
  46479. default:
  46480. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  46481. return;
  46482. }
  46483. }
  46484. mipmapCount = 1;
  46485. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  46486. mipmapCount = Math.max(1, header[off_mipmapCount]);
  46487. }
  46488. var bpp = header[off_RGBbpp];
  46489. for (var face = 0; face < faces; face++) {
  46490. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  46491. width = header[off_width];
  46492. height = header[off_height];
  46493. dataOffset = header[off_size] + 4;
  46494. for (i = 0; i < mipmapCount; ++i) {
  46495. if (info.isRGB) {
  46496. if (bpp === 24) {
  46497. dataLength = width * height * 3;
  46498. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  46499. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  46500. }
  46501. else {
  46502. dataLength = width * height * 4;
  46503. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  46504. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  46505. }
  46506. }
  46507. else if (info.isLuminance) {
  46508. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  46509. var unpaddedRowSize = width;
  46510. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  46511. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  46512. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  46513. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  46514. }
  46515. else {
  46516. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  46517. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  46518. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  46519. }
  46520. dataOffset += dataLength;
  46521. width *= 0.5;
  46522. height *= 0.5;
  46523. width = Math.max(1.0, width);
  46524. height = Math.max(1.0, height);
  46525. }
  46526. }
  46527. };
  46528. return DDSTools;
  46529. }());
  46530. Internals.DDSTools = DDSTools;
  46531. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46532. })(BABYLON || (BABYLON = {}));
  46533. //# sourceMappingURL=babylon.tools.dds.js.map
  46534. var BABYLON;
  46535. (function (BABYLON) {
  46536. var Internals;
  46537. (function (Internals) {
  46538. /**
  46539. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  46540. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  46541. */
  46542. var KhronosTextureContainer = (function () {
  46543. /**
  46544. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  46545. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  46546. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  46547. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  46548. */
  46549. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  46550. this.arrayBuffer = arrayBuffer;
  46551. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  46552. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  46553. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  46554. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  46555. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  46556. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  46557. BABYLON.Tools.Error("texture missing KTX identifier");
  46558. return;
  46559. }
  46560. // load the reset of the header in native 32 bit int
  46561. var header = new Int32Array(this.arrayBuffer, 12, 13);
  46562. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  46563. var oppositeEndianess = header[0] === 0x01020304;
  46564. // read all the header elements in order they exist in the file, without modification (sans endainness)
  46565. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  46566. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  46567. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  46568. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  46569. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  46570. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  46571. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  46572. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  46573. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  46574. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  46575. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  46576. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  46577. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  46578. if (this.glType !== 0) {
  46579. BABYLON.Tools.Error("only compressed formats currently supported");
  46580. return;
  46581. }
  46582. else {
  46583. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  46584. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  46585. }
  46586. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  46587. BABYLON.Tools.Error("only 2D textures currently supported");
  46588. return;
  46589. }
  46590. if (this.numberOfArrayElements !== 0) {
  46591. BABYLON.Tools.Error("texture arrays not currently supported");
  46592. return;
  46593. }
  46594. if (this.numberOfFaces !== facesExpected) {
  46595. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  46596. return;
  46597. }
  46598. // we now have a completely validated file, so could use existence of loadType as success
  46599. // would need to make this more elaborate & adjust checks above to support more than one load type
  46600. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  46601. }
  46602. // not as fast hardware based, but will probably never need to use
  46603. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  46604. return ((val & 0xFF) << 24)
  46605. | ((val & 0xFF00) << 8)
  46606. | ((val >> 8) & 0xFF00)
  46607. | ((val >> 24) & 0xFF);
  46608. };
  46609. /**
  46610. * It is assumed that the texture has already been created & is currently bound
  46611. */
  46612. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  46613. switch (this.loadType) {
  46614. case KhronosTextureContainer.COMPRESSED_2D:
  46615. this._upload2DCompressedLevels(gl, loadMipmaps);
  46616. break;
  46617. case KhronosTextureContainer.TEX_2D:
  46618. case KhronosTextureContainer.COMPRESSED_3D:
  46619. case KhronosTextureContainer.TEX_3D:
  46620. }
  46621. };
  46622. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  46623. // initialize width & height for level 1
  46624. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  46625. var width = this.pixelWidth;
  46626. var height = this.pixelHeight;
  46627. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  46628. for (var level = 0; level < mipmapCount; level++) {
  46629. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  46630. for (var face = 0; face < this.numberOfFaces; face++) {
  46631. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  46632. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  46633. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  46634. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  46635. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  46636. }
  46637. width = Math.max(1.0, width * 0.5);
  46638. height = Math.max(1.0, height * 0.5);
  46639. }
  46640. };
  46641. return KhronosTextureContainer;
  46642. }());
  46643. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  46644. // load types
  46645. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  46646. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  46647. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  46648. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  46649. Internals.KhronosTextureContainer = KhronosTextureContainer;
  46650. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46651. })(BABYLON || (BABYLON = {}));
  46652. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  46653. var BABYLON;
  46654. (function (BABYLON) {
  46655. var CannonJSPlugin = (function () {
  46656. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  46657. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  46658. if (iterations === void 0) { iterations = 10; }
  46659. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  46660. this.name = "CannonJSPlugin";
  46661. this._physicsMaterials = [];
  46662. this._fixedTimeStep = 1 / 60;
  46663. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  46664. this._currentCollisionGroup = 2;
  46665. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  46666. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  46667. this._tmpPosition = BABYLON.Vector3.Zero();
  46668. this._tmpQuaternion = new BABYLON.Quaternion();
  46669. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  46670. this._tmpDeltaRotation = new BABYLON.Quaternion();
  46671. this._tmpUnityRotation = new BABYLON.Quaternion();
  46672. if (!this.isSupported()) {
  46673. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  46674. return;
  46675. }
  46676. this.world = new CANNON.World();
  46677. this.world.broadphase = new CANNON.NaiveBroadphase();
  46678. this.world.solver.iterations = iterations;
  46679. }
  46680. CannonJSPlugin.prototype.setGravity = function (gravity) {
  46681. this.world.gravity.copy(gravity);
  46682. };
  46683. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  46684. this._fixedTimeStep = timeStep;
  46685. };
  46686. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  46687. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  46688. };
  46689. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  46690. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  46691. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  46692. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  46693. };
  46694. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  46695. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  46696. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  46697. impostor.physicsBody.applyForce(impulse, worldPoint);
  46698. };
  46699. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  46700. //parent-child relationship. Does this impostor has a parent impostor?
  46701. if (impostor.parent) {
  46702. if (impostor.physicsBody) {
  46703. this.removePhysicsBody(impostor);
  46704. //TODO is that needed?
  46705. impostor.forceUpdate();
  46706. }
  46707. return;
  46708. }
  46709. //should a new body be created for this impostor?
  46710. if (impostor.isBodyInitRequired()) {
  46711. var shape = this._createShape(impostor);
  46712. //unregister events, if body is being changed
  46713. var oldBody = impostor.physicsBody;
  46714. if (oldBody) {
  46715. this.removePhysicsBody(impostor);
  46716. }
  46717. //create the body and material
  46718. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  46719. var bodyCreationObject = {
  46720. mass: impostor.getParam("mass"),
  46721. material: material
  46722. };
  46723. // A simple extend, in case native options were used.
  46724. var nativeOptions = impostor.getParam("nativeOptions");
  46725. for (var key in nativeOptions) {
  46726. if (nativeOptions.hasOwnProperty(key)) {
  46727. bodyCreationObject[key] = nativeOptions[key];
  46728. }
  46729. }
  46730. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  46731. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  46732. this.world.addEventListener("preStep", impostor.beforeStep);
  46733. this.world.addEventListener("postStep", impostor.afterStep);
  46734. impostor.physicsBody.addShape(shape);
  46735. this.world.add(impostor.physicsBody);
  46736. //try to keep the body moving in the right direction by taking old properties.
  46737. //Should be tested!
  46738. if (oldBody) {
  46739. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  46740. impostor.physicsBody[param].copy(oldBody[param]);
  46741. });
  46742. }
  46743. this._processChildMeshes(impostor);
  46744. }
  46745. //now update the body's transformation
  46746. this._updatePhysicsBodyTransformation(impostor);
  46747. };
  46748. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  46749. var _this = this;
  46750. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  46751. if (meshChildren.length) {
  46752. var processMesh = function (localPosition, mesh) {
  46753. var childImpostor = mesh.getPhysicsImpostor();
  46754. if (childImpostor) {
  46755. var parent = childImpostor.parent;
  46756. if (parent !== mainImpostor) {
  46757. var localPosition = mesh.position;
  46758. if (childImpostor.physicsBody) {
  46759. _this.removePhysicsBody(childImpostor);
  46760. childImpostor.physicsBody = null;
  46761. }
  46762. childImpostor.parent = mainImpostor;
  46763. childImpostor.resetUpdateFlags();
  46764. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  46765. //Add the mass of the children.
  46766. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  46767. }
  46768. }
  46769. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  46770. };
  46771. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  46772. }
  46773. };
  46774. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  46775. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  46776. this.world.removeEventListener("preStep", impostor.beforeStep);
  46777. this.world.removeEventListener("postStep", impostor.afterStep);
  46778. this.world.remove(impostor.physicsBody);
  46779. };
  46780. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  46781. var mainBody = impostorJoint.mainImpostor.physicsBody;
  46782. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  46783. if (!mainBody || !connectedBody) {
  46784. return;
  46785. }
  46786. var constraint;
  46787. var jointData = impostorJoint.joint.jointData;
  46788. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  46789. var constraintData = {
  46790. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  46791. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  46792. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  46793. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  46794. maxForce: jointData.nativeParams.maxForce,
  46795. collideConnected: !!jointData.collision
  46796. };
  46797. switch (impostorJoint.joint.type) {
  46798. case BABYLON.PhysicsJoint.HingeJoint:
  46799. case BABYLON.PhysicsJoint.Hinge2Joint:
  46800. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  46801. break;
  46802. case BABYLON.PhysicsJoint.DistanceJoint:
  46803. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  46804. break;
  46805. case BABYLON.PhysicsJoint.SpringJoint:
  46806. var springData = jointData;
  46807. constraint = new CANNON.Spring(mainBody, connectedBody, {
  46808. restLength: springData.length,
  46809. stiffness: springData.stiffness,
  46810. damping: springData.damping,
  46811. localAnchorA: constraintData.pivotA,
  46812. localAnchorB: constraintData.pivotB
  46813. });
  46814. break;
  46815. case BABYLON.PhysicsJoint.LockJoint:
  46816. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  46817. break;
  46818. case BABYLON.PhysicsJoint.PointToPointJoint:
  46819. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  46820. default:
  46821. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  46822. break;
  46823. }
  46824. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  46825. constraint.collideConnected = !!jointData.collision;
  46826. impostorJoint.joint.physicsJoint = constraint;
  46827. //don't add spring as constraint, as it is not one.
  46828. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  46829. this.world.addConstraint(constraint);
  46830. }
  46831. else {
  46832. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  46833. constraint.applyForce();
  46834. });
  46835. }
  46836. };
  46837. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  46838. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  46839. };
  46840. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  46841. var index;
  46842. var mat;
  46843. for (index = 0; index < this._physicsMaterials.length; index++) {
  46844. mat = this._physicsMaterials[index];
  46845. if (mat.friction === friction && mat.restitution === restitution) {
  46846. return mat;
  46847. }
  46848. }
  46849. var currentMat = new CANNON.Material(name);
  46850. currentMat.friction = friction;
  46851. currentMat.restitution = restitution;
  46852. this._physicsMaterials.push(currentMat);
  46853. return currentMat;
  46854. };
  46855. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  46856. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  46857. };
  46858. CannonJSPlugin.prototype._createShape = function (impostor) {
  46859. var object = impostor.object;
  46860. var returnValue;
  46861. var extendSize = impostor.getObjectExtendSize();
  46862. switch (impostor.type) {
  46863. case BABYLON.PhysicsImpostor.SphereImpostor:
  46864. var radiusX = extendSize.x;
  46865. var radiusY = extendSize.y;
  46866. var radiusZ = extendSize.z;
  46867. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  46868. break;
  46869. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  46870. case BABYLON.PhysicsImpostor.CylinderImpostor:
  46871. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  46872. break;
  46873. case BABYLON.PhysicsImpostor.BoxImpostor:
  46874. var box = extendSize.scale(0.5);
  46875. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  46876. break;
  46877. case BABYLON.PhysicsImpostor.PlaneImpostor:
  46878. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  46879. returnValue = new CANNON.Plane();
  46880. break;
  46881. case BABYLON.PhysicsImpostor.MeshImpostor:
  46882. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  46883. var rawFaces = object.getIndices ? object.getIndices() : [];
  46884. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  46885. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  46886. break;
  46887. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  46888. returnValue = this._createHeightmap(object);
  46889. break;
  46890. case BABYLON.PhysicsImpostor.ParticleImpostor:
  46891. returnValue = new CANNON.Particle();
  46892. break;
  46893. }
  46894. return returnValue;
  46895. };
  46896. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  46897. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46898. var matrix = [];
  46899. //For now pointDepth will not be used and will be automatically calculated.
  46900. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  46901. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  46902. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  46903. var elementSize = dim * 2 / arraySize;
  46904. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  46905. for (var i = 0; i < pos.length; i = i + 3) {
  46906. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  46907. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  46908. var y = pos[i + 1] + minY;
  46909. if (!matrix[x]) {
  46910. matrix[x] = [];
  46911. }
  46912. if (!matrix[x][z]) {
  46913. matrix[x][z] = y;
  46914. }
  46915. matrix[x][z] = Math.max(y, matrix[x][z]);
  46916. }
  46917. for (var x = 0; x <= arraySize; ++x) {
  46918. if (!matrix[x]) {
  46919. var loc = 1;
  46920. while (!matrix[(x + loc) % arraySize]) {
  46921. loc++;
  46922. }
  46923. matrix[x] = matrix[(x + loc) % arraySize].slice();
  46924. //console.log("missing x", x);
  46925. }
  46926. for (var z = 0; z <= arraySize; ++z) {
  46927. if (!matrix[x][z]) {
  46928. var loc = 1;
  46929. var newValue;
  46930. while (newValue === undefined) {
  46931. newValue = matrix[x][(z + loc++) % arraySize];
  46932. }
  46933. matrix[x][z] = newValue;
  46934. }
  46935. }
  46936. }
  46937. var shape = new CANNON.Heightfield(matrix, {
  46938. elementSize: elementSize
  46939. });
  46940. //For future reference, needed for body transformation
  46941. shape.minY = minY;
  46942. return shape;
  46943. };
  46944. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  46945. var object = impostor.object;
  46946. //make sure it is updated...
  46947. object.computeWorldMatrix && object.computeWorldMatrix(true);
  46948. // The delta between the mesh position and the mesh bounding box center
  46949. var center = impostor.getObjectCenter();
  46950. var extendSize = impostor.getObjectExtendSize();
  46951. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  46952. this._tmpPosition.copyFrom(center);
  46953. var quaternion = object.rotationQuaternion;
  46954. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  46955. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  46956. //-90 DEG in X, precalculated
  46957. quaternion = quaternion.multiply(this._minus90X);
  46958. //Invert! (Precalculated, 90 deg in X)
  46959. //No need to clone. this will never change.
  46960. impostor.setDeltaRotation(this._plus90X);
  46961. }
  46962. //If it is a heightfield, if should be centered.
  46963. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  46964. var mesh = object;
  46965. //calculate the correct body position:
  46966. var rotationQuaternion = mesh.rotationQuaternion;
  46967. mesh.rotationQuaternion = this._tmpUnityRotation;
  46968. mesh.computeWorldMatrix(true);
  46969. //get original center with no rotation
  46970. var c = center.clone();
  46971. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  46972. //rotation is back
  46973. mesh.rotationQuaternion = rotationQuaternion;
  46974. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  46975. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  46976. mesh.setPivotMatrix(p);
  46977. mesh.computeWorldMatrix(true);
  46978. //calculate the translation
  46979. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  46980. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  46981. //add it inverted to the delta
  46982. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  46983. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  46984. mesh.setPivotMatrix(oldPivot);
  46985. mesh.computeWorldMatrix(true);
  46986. }
  46987. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  46988. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  46989. this._tmpPosition.copyFrom(object.position);
  46990. }
  46991. impostor.setDeltaPosition(this._tmpDeltaPosition);
  46992. //Now update the impostor object
  46993. impostor.physicsBody.position.copy(this._tmpPosition);
  46994. impostor.physicsBody.quaternion.copy(quaternion);
  46995. };
  46996. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  46997. impostor.object.position.copyFrom(impostor.physicsBody.position);
  46998. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  46999. };
  47000. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  47001. impostor.physicsBody.position.copy(newPosition);
  47002. impostor.physicsBody.quaternion.copy(newRotation);
  47003. };
  47004. CannonJSPlugin.prototype.isSupported = function () {
  47005. return window.CANNON !== undefined;
  47006. };
  47007. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  47008. impostor.physicsBody.velocity.copy(velocity);
  47009. };
  47010. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  47011. impostor.physicsBody.angularVelocity.copy(velocity);
  47012. };
  47013. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  47014. var v = impostor.physicsBody.velocity;
  47015. if (!v)
  47016. return null;
  47017. return new BABYLON.Vector3(v.x, v.y, v.z);
  47018. };
  47019. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  47020. var v = impostor.physicsBody.angularVelocity;
  47021. if (!v)
  47022. return null;
  47023. return new BABYLON.Vector3(v.x, v.y, v.z);
  47024. };
  47025. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  47026. impostor.physicsBody.mass = mass;
  47027. impostor.physicsBody.updateMassProperties();
  47028. };
  47029. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  47030. impostor.physicsBody.sleep();
  47031. };
  47032. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  47033. impostor.physicsBody.wakeUp();
  47034. };
  47035. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  47036. joint.physicsJoint.distance = maxDistance;
  47037. };
  47038. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  47039. if (!motorIndex) {
  47040. joint.physicsJoint.enableMotor();
  47041. }
  47042. };
  47043. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  47044. if (!motorIndex) {
  47045. joint.physicsJoint.disableMotor();
  47046. }
  47047. };
  47048. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  47049. if (!motorIndex) {
  47050. joint.physicsJoint.enableMotor();
  47051. joint.physicsJoint.setMotorSpeed(speed);
  47052. if (maxForce) {
  47053. this.setLimit(joint, maxForce);
  47054. }
  47055. }
  47056. };
  47057. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  47058. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  47059. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  47060. };
  47061. CannonJSPlugin.prototype.dispose = function () {
  47062. //nothing to do, actually.
  47063. };
  47064. return CannonJSPlugin;
  47065. }());
  47066. BABYLON.CannonJSPlugin = CannonJSPlugin;
  47067. })(BABYLON || (BABYLON = {}));
  47068. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  47069. var BABYLON;
  47070. (function (BABYLON) {
  47071. var OimoJSPlugin = (function () {
  47072. function OimoJSPlugin(iterations) {
  47073. this.name = "OimoJSPlugin";
  47074. this._tmpImpostorsArray = [];
  47075. this._tmpPositionVector = BABYLON.Vector3.Zero();
  47076. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  47077. this.world.worldscale(1);
  47078. this.world.clear();
  47079. //making sure no stats are calculated
  47080. this.world.isNoStat = true;
  47081. }
  47082. OimoJSPlugin.prototype.setGravity = function (gravity) {
  47083. this.world.gravity.copy(gravity);
  47084. };
  47085. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  47086. this.world.timeStep = timeStep;
  47087. };
  47088. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  47089. var _this = this;
  47090. impostors.forEach(function (impostor) {
  47091. impostor.beforeStep();
  47092. });
  47093. this.world.step();
  47094. impostors.forEach(function (impostor) {
  47095. impostor.afterStep();
  47096. //update the ordered impostors array
  47097. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  47098. });
  47099. //check for collisions
  47100. var contact = this.world.contacts;
  47101. while (contact !== null) {
  47102. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  47103. contact = contact.next;
  47104. continue;
  47105. }
  47106. //is this body colliding with any other? get the impostor
  47107. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  47108. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  47109. if (!mainImpostor || !collidingImpostor) {
  47110. contact = contact.next;
  47111. continue;
  47112. }
  47113. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  47114. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  47115. contact = contact.next;
  47116. }
  47117. };
  47118. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  47119. var mass = impostor.physicsBody.massInfo.mass;
  47120. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  47121. };
  47122. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  47123. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  47124. this.applyImpulse(impostor, force, contactPoint);
  47125. };
  47126. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  47127. var _this = this;
  47128. //parent-child relationship. Does this impostor has a parent impostor?
  47129. if (impostor.parent) {
  47130. if (impostor.physicsBody) {
  47131. this.removePhysicsBody(impostor);
  47132. //TODO is that needed?
  47133. impostor.forceUpdate();
  47134. }
  47135. return;
  47136. }
  47137. if (impostor.isBodyInitRequired()) {
  47138. var bodyConfig = {
  47139. name: impostor.uniqueId,
  47140. //Oimo must have mass, also for static objects.
  47141. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  47142. size: [],
  47143. type: [],
  47144. pos: [],
  47145. rot: [],
  47146. move: impostor.getParam("mass") !== 0,
  47147. //Supporting older versions of Oimo
  47148. world: this.world
  47149. };
  47150. var impostors = [impostor];
  47151. var addToArray = function (parent) {
  47152. if (!parent.getChildMeshes)
  47153. return;
  47154. parent.getChildMeshes().forEach(function (m) {
  47155. if (m.physicsImpostor) {
  47156. impostors.push(m.physicsImpostor);
  47157. m.physicsImpostor._init();
  47158. }
  47159. });
  47160. };
  47161. addToArray(impostor.object);
  47162. var checkWithEpsilon_1 = function (value) {
  47163. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  47164. };
  47165. impostors.forEach(function (i) {
  47166. //get the correct bounding box
  47167. var oldQuaternion = i.object.rotationQuaternion;
  47168. var rot = new OIMO.Euler().setFromQuaternion({
  47169. x: impostor.object.rotationQuaternion.x,
  47170. y: impostor.object.rotationQuaternion.y,
  47171. z: impostor.object.rotationQuaternion.z,
  47172. s: impostor.object.rotationQuaternion.w
  47173. });
  47174. var extendSize = i.getObjectExtendSize();
  47175. if (i === impostor) {
  47176. var center = impostor.getObjectCenter();
  47177. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  47178. //Can also use Array.prototype.push.apply
  47179. bodyConfig.pos.push(center.x);
  47180. bodyConfig.pos.push(center.y);
  47181. bodyConfig.pos.push(center.z);
  47182. //tmp solution
  47183. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  47184. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  47185. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  47186. }
  47187. else {
  47188. bodyConfig.pos.push(i.object.position.x);
  47189. bodyConfig.pos.push(i.object.position.y);
  47190. bodyConfig.pos.push(i.object.position.z);
  47191. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  47192. bodyConfig.rot.push(0);
  47193. bodyConfig.rot.push(0);
  47194. bodyConfig.rot.push(0);
  47195. }
  47196. // register mesh
  47197. switch (i.type) {
  47198. case BABYLON.PhysicsImpostor.ParticleImpostor:
  47199. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  47200. case BABYLON.PhysicsImpostor.SphereImpostor:
  47201. var radiusX = extendSize.x;
  47202. var radiusY = extendSize.y;
  47203. var radiusZ = extendSize.z;
  47204. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  47205. bodyConfig.type.push('sphere');
  47206. //due to the way oimo works with compounds, add 3 times
  47207. bodyConfig.size.push(size);
  47208. bodyConfig.size.push(size);
  47209. bodyConfig.size.push(size);
  47210. break;
  47211. case BABYLON.PhysicsImpostor.CylinderImpostor:
  47212. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  47213. var sizeY = checkWithEpsilon_1(extendSize.y);
  47214. bodyConfig.type.push('cylinder');
  47215. bodyConfig.size.push(sizeX);
  47216. bodyConfig.size.push(sizeY);
  47217. //due to the way oimo works with compounds, add one more value.
  47218. bodyConfig.size.push(sizeY);
  47219. break;
  47220. case BABYLON.PhysicsImpostor.PlaneImpostor:
  47221. case BABYLON.PhysicsImpostor.BoxImpostor:
  47222. default:
  47223. var sizeX = checkWithEpsilon_1(extendSize.x);
  47224. var sizeY = checkWithEpsilon_1(extendSize.y);
  47225. var sizeZ = checkWithEpsilon_1(extendSize.z);
  47226. bodyConfig.type.push('box');
  47227. bodyConfig.size.push(sizeX);
  47228. bodyConfig.size.push(sizeY);
  47229. bodyConfig.size.push(sizeZ);
  47230. break;
  47231. }
  47232. //actually not needed, but hey...
  47233. i.object.rotationQuaternion = oldQuaternion;
  47234. });
  47235. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  47236. }
  47237. else {
  47238. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  47239. }
  47240. impostor.setDeltaPosition(this._tmpPositionVector);
  47241. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  47242. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  47243. };
  47244. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  47245. //impostor.physicsBody.dispose();
  47246. //Same as : (older oimo versions)
  47247. this.world.removeRigidBody(impostor.physicsBody);
  47248. };
  47249. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  47250. var mainBody = impostorJoint.mainImpostor.physicsBody;
  47251. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  47252. if (!mainBody || !connectedBody) {
  47253. return;
  47254. }
  47255. var jointData = impostorJoint.joint.jointData;
  47256. var options = jointData.nativeParams || {};
  47257. var type;
  47258. var nativeJointData = {
  47259. body1: mainBody,
  47260. body2: connectedBody,
  47261. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  47262. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  47263. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  47264. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  47265. min: options.min,
  47266. max: options.max,
  47267. collision: options.collision || jointData.collision,
  47268. spring: options.spring,
  47269. //supporting older version of Oimo
  47270. world: this.world
  47271. };
  47272. switch (impostorJoint.joint.type) {
  47273. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  47274. type = "jointBall";
  47275. break;
  47276. case BABYLON.PhysicsJoint.SpringJoint:
  47277. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  47278. var springData = jointData;
  47279. nativeJointData.min = springData.length || nativeJointData.min;
  47280. //Max should also be set, just make sure it is at least min
  47281. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  47282. case BABYLON.PhysicsJoint.DistanceJoint:
  47283. type = "jointDistance";
  47284. nativeJointData.max = jointData.maxDistance;
  47285. break;
  47286. case BABYLON.PhysicsJoint.PrismaticJoint:
  47287. type = "jointPrisme";
  47288. break;
  47289. case BABYLON.PhysicsJoint.SliderJoint:
  47290. type = "jointSlide";
  47291. break;
  47292. case BABYLON.PhysicsJoint.WheelJoint:
  47293. type = "jointWheel";
  47294. break;
  47295. case BABYLON.PhysicsJoint.HingeJoint:
  47296. default:
  47297. type = "jointHinge";
  47298. break;
  47299. }
  47300. nativeJointData.type = type;
  47301. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  47302. };
  47303. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  47304. //Bug in Oimo prevents us from disposing a joint in the playground
  47305. //joint.joint.physicsJoint.dispose();
  47306. //So we will bruteforce it!
  47307. try {
  47308. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  47309. }
  47310. catch (e) {
  47311. BABYLON.Tools.Warn(e);
  47312. }
  47313. };
  47314. OimoJSPlugin.prototype.isSupported = function () {
  47315. return OIMO !== undefined;
  47316. };
  47317. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  47318. if (!impostor.physicsBody.sleeping) {
  47319. //TODO check that
  47320. if (impostor.physicsBody.shapes.next) {
  47321. var parentShape = this._getLastShape(impostor.physicsBody);
  47322. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  47323. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  47324. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  47325. }
  47326. else {
  47327. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  47328. }
  47329. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  47330. impostor.object.rotationQuaternion.normalize();
  47331. }
  47332. };
  47333. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  47334. var body = impostor.physicsBody;
  47335. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  47336. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  47337. body.syncShapes();
  47338. body.awake();
  47339. };
  47340. OimoJSPlugin.prototype._getLastShape = function (body) {
  47341. var lastShape = body.shapes;
  47342. while (lastShape.next) {
  47343. lastShape = lastShape.next;
  47344. }
  47345. return lastShape;
  47346. };
  47347. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  47348. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  47349. };
  47350. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  47351. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  47352. };
  47353. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  47354. var v = impostor.physicsBody.linearVelocity;
  47355. if (!v)
  47356. return null;
  47357. return new BABYLON.Vector3(v.x, v.y, v.z);
  47358. };
  47359. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  47360. var v = impostor.physicsBody.angularVelocity;
  47361. if (!v)
  47362. return null;
  47363. return new BABYLON.Vector3(v.x, v.y, v.z);
  47364. };
  47365. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  47366. var staticBody = mass === 0;
  47367. //this will actually set the body's density and not its mass.
  47368. //But this is how oimo treats the mass variable.
  47369. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  47370. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  47371. };
  47372. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  47373. impostor.physicsBody.sleep();
  47374. };
  47375. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  47376. impostor.physicsBody.awake();
  47377. };
  47378. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  47379. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  47380. if (minDistance !== void 0) {
  47381. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  47382. }
  47383. };
  47384. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  47385. //TODO separate rotational and transational motors.
  47386. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  47387. if (motor) {
  47388. motor.setMotor(speed, maxForce);
  47389. }
  47390. };
  47391. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  47392. //TODO separate rotational and transational motors.
  47393. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  47394. if (motor) {
  47395. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  47396. }
  47397. };
  47398. OimoJSPlugin.prototype.dispose = function () {
  47399. this.world.clear();
  47400. };
  47401. return OimoJSPlugin;
  47402. }());
  47403. BABYLON.OimoJSPlugin = OimoJSPlugin;
  47404. })(BABYLON || (BABYLON = {}));
  47405. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  47406. var BABYLON;
  47407. (function (BABYLON) {
  47408. var DisplayPassPostProcess = (function (_super) {
  47409. __extends(DisplayPassPostProcess, _super);
  47410. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  47411. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  47412. }
  47413. return DisplayPassPostProcess;
  47414. }(BABYLON.PostProcess));
  47415. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  47416. })(BABYLON || (BABYLON = {}));
  47417. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  47418. var BABYLON;
  47419. (function (BABYLON) {
  47420. var SimplificationSettings = (function () {
  47421. function SimplificationSettings(quality, distance, optimizeMesh) {
  47422. this.quality = quality;
  47423. this.distance = distance;
  47424. this.optimizeMesh = optimizeMesh;
  47425. }
  47426. return SimplificationSettings;
  47427. }());
  47428. BABYLON.SimplificationSettings = SimplificationSettings;
  47429. var SimplificationQueue = (function () {
  47430. function SimplificationQueue() {
  47431. this.running = false;
  47432. this._simplificationArray = [];
  47433. }
  47434. SimplificationQueue.prototype.addTask = function (task) {
  47435. this._simplificationArray.push(task);
  47436. };
  47437. SimplificationQueue.prototype.executeNext = function () {
  47438. var task = this._simplificationArray.pop();
  47439. if (task) {
  47440. this.running = true;
  47441. this.runSimplification(task);
  47442. }
  47443. else {
  47444. this.running = false;
  47445. }
  47446. };
  47447. SimplificationQueue.prototype.runSimplification = function (task) {
  47448. var _this = this;
  47449. if (task.parallelProcessing) {
  47450. //parallel simplifier
  47451. task.settings.forEach(function (setting) {
  47452. var simplifier = _this.getSimplifier(task);
  47453. simplifier.simplify(setting, function (newMesh) {
  47454. task.mesh.addLODLevel(setting.distance, newMesh);
  47455. newMesh.isVisible = true;
  47456. //check if it is the last
  47457. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  47458. //all done, run the success callback.
  47459. task.successCallback();
  47460. }
  47461. _this.executeNext();
  47462. });
  47463. });
  47464. }
  47465. else {
  47466. //single simplifier.
  47467. var simplifier = this.getSimplifier(task);
  47468. var runDecimation = function (setting, callback) {
  47469. simplifier.simplify(setting, function (newMesh) {
  47470. task.mesh.addLODLevel(setting.distance, newMesh);
  47471. newMesh.isVisible = true;
  47472. //run the next quality level
  47473. callback();
  47474. });
  47475. };
  47476. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  47477. runDecimation(task.settings[loop.index], function () {
  47478. loop.executeNext();
  47479. });
  47480. }, function () {
  47481. //execution ended, run the success callback.
  47482. if (task.successCallback) {
  47483. task.successCallback();
  47484. }
  47485. _this.executeNext();
  47486. });
  47487. }
  47488. };
  47489. SimplificationQueue.prototype.getSimplifier = function (task) {
  47490. switch (task.simplificationType) {
  47491. case SimplificationType.QUADRATIC:
  47492. default:
  47493. return new QuadraticErrorSimplification(task.mesh);
  47494. }
  47495. };
  47496. return SimplificationQueue;
  47497. }());
  47498. BABYLON.SimplificationQueue = SimplificationQueue;
  47499. /**
  47500. * The implemented types of simplification.
  47501. * At the moment only Quadratic Error Decimation is implemented.
  47502. */
  47503. var SimplificationType;
  47504. (function (SimplificationType) {
  47505. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  47506. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  47507. var DecimationTriangle = (function () {
  47508. function DecimationTriangle(vertices) {
  47509. this.vertices = vertices;
  47510. this.error = new Array(4);
  47511. this.deleted = false;
  47512. this.isDirty = false;
  47513. this.deletePending = false;
  47514. this.borderFactor = 0;
  47515. }
  47516. return DecimationTriangle;
  47517. }());
  47518. BABYLON.DecimationTriangle = DecimationTriangle;
  47519. var DecimationVertex = (function () {
  47520. function DecimationVertex(position, id) {
  47521. this.position = position;
  47522. this.id = id;
  47523. this.isBorder = true;
  47524. this.q = new QuadraticMatrix();
  47525. this.triangleCount = 0;
  47526. this.triangleStart = 0;
  47527. this.originalOffsets = [];
  47528. }
  47529. DecimationVertex.prototype.updatePosition = function (newPosition) {
  47530. this.position.copyFrom(newPosition);
  47531. };
  47532. return DecimationVertex;
  47533. }());
  47534. BABYLON.DecimationVertex = DecimationVertex;
  47535. var QuadraticMatrix = (function () {
  47536. function QuadraticMatrix(data) {
  47537. this.data = new Array(10);
  47538. for (var i = 0; i < 10; ++i) {
  47539. if (data && data[i]) {
  47540. this.data[i] = data[i];
  47541. }
  47542. else {
  47543. this.data[i] = 0;
  47544. }
  47545. }
  47546. }
  47547. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  47548. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  47549. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  47550. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  47551. return det;
  47552. };
  47553. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  47554. for (var i = 0; i < 10; ++i) {
  47555. this.data[i] += matrix.data[i];
  47556. }
  47557. };
  47558. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  47559. for (var i = 0; i < 10; ++i) {
  47560. this.data[i] += data[i];
  47561. }
  47562. };
  47563. QuadraticMatrix.prototype.add = function (matrix) {
  47564. var m = new QuadraticMatrix();
  47565. for (var i = 0; i < 10; ++i) {
  47566. m.data[i] = this.data[i] + matrix.data[i];
  47567. }
  47568. return m;
  47569. };
  47570. QuadraticMatrix.FromData = function (a, b, c, d) {
  47571. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  47572. };
  47573. //returning an array to avoid garbage collection
  47574. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  47575. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  47576. };
  47577. return QuadraticMatrix;
  47578. }());
  47579. BABYLON.QuadraticMatrix = QuadraticMatrix;
  47580. var Reference = (function () {
  47581. function Reference(vertexId, triangleId) {
  47582. this.vertexId = vertexId;
  47583. this.triangleId = triangleId;
  47584. }
  47585. return Reference;
  47586. }());
  47587. BABYLON.Reference = Reference;
  47588. /**
  47589. * An implementation of the Quadratic Error simplification algorithm.
  47590. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  47591. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  47592. * @author RaananW
  47593. */
  47594. var QuadraticErrorSimplification = (function () {
  47595. function QuadraticErrorSimplification(_mesh) {
  47596. this._mesh = _mesh;
  47597. this.initialized = false;
  47598. this.syncIterations = 5000;
  47599. this.aggressiveness = 7;
  47600. this.decimationIterations = 100;
  47601. this.boundingBoxEpsilon = BABYLON.Epsilon;
  47602. }
  47603. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  47604. var _this = this;
  47605. this.initDecimatedMesh();
  47606. //iterating through the submeshes array, one after the other.
  47607. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  47608. _this.initWithMesh(loop.index, function () {
  47609. _this.runDecimation(settings, loop.index, function () {
  47610. loop.executeNext();
  47611. });
  47612. }, settings.optimizeMesh);
  47613. }, function () {
  47614. setTimeout(function () {
  47615. successCallback(_this._reconstructedMesh);
  47616. }, 0);
  47617. });
  47618. };
  47619. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  47620. var _this = this;
  47621. var gCount = 0;
  47622. triangle.vertices.forEach(function (vertex) {
  47623. var count = 0;
  47624. var vPos = vertex.position;
  47625. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  47626. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  47627. ++count;
  47628. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  47629. ++count;
  47630. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  47631. ++count;
  47632. if (count > 1) {
  47633. ++gCount;
  47634. }
  47635. ;
  47636. });
  47637. if (gCount > 1) {
  47638. console.log(triangle, gCount);
  47639. }
  47640. return gCount > 1;
  47641. };
  47642. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  47643. var _this = this;
  47644. var targetCount = ~~(this.triangles.length * settings.quality);
  47645. var deletedTriangles = 0;
  47646. var triangleCount = this.triangles.length;
  47647. var iterationFunction = function (iteration, callback) {
  47648. setTimeout(function () {
  47649. if (iteration % 5 === 0) {
  47650. _this.updateMesh(iteration === 0);
  47651. }
  47652. for (var i = 0; i < _this.triangles.length; ++i) {
  47653. _this.triangles[i].isDirty = false;
  47654. }
  47655. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  47656. var trianglesIterator = function (i) {
  47657. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  47658. var t = _this.triangles[tIdx];
  47659. if (!t)
  47660. return;
  47661. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  47662. return;
  47663. }
  47664. for (var j = 0; j < 3; ++j) {
  47665. if (t.error[j] < threshold) {
  47666. var deleted0 = [];
  47667. var deleted1 = [];
  47668. var v0 = t.vertices[j];
  47669. var v1 = t.vertices[(j + 1) % 3];
  47670. if (v0.isBorder || v1.isBorder)
  47671. continue;
  47672. var p = BABYLON.Vector3.Zero();
  47673. var n = BABYLON.Vector3.Zero();
  47674. var uv = BABYLON.Vector2.Zero();
  47675. var color = new BABYLON.Color4(0, 0, 0, 1);
  47676. _this.calculateError(v0, v1, p, n, uv, color);
  47677. var delTr = [];
  47678. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  47679. continue;
  47680. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  47681. continue;
  47682. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  47683. continue;
  47684. var uniqueArray = [];
  47685. delTr.forEach(function (deletedT) {
  47686. if (uniqueArray.indexOf(deletedT) === -1) {
  47687. deletedT.deletePending = true;
  47688. uniqueArray.push(deletedT);
  47689. }
  47690. });
  47691. if (uniqueArray.length % 2 !== 0) {
  47692. continue;
  47693. }
  47694. v0.q = v1.q.add(v0.q);
  47695. v0.updatePosition(p);
  47696. var tStart = _this.references.length;
  47697. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  47698. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  47699. var tCount = _this.references.length - tStart;
  47700. if (tCount <= v0.triangleCount) {
  47701. if (tCount) {
  47702. for (var c = 0; c < tCount; c++) {
  47703. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  47704. }
  47705. }
  47706. }
  47707. else {
  47708. v0.triangleStart = tStart;
  47709. }
  47710. v0.triangleCount = tCount;
  47711. break;
  47712. }
  47713. }
  47714. };
  47715. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  47716. }, 0);
  47717. };
  47718. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  47719. if (triangleCount - deletedTriangles <= targetCount)
  47720. loop.breakLoop();
  47721. else {
  47722. iterationFunction(loop.index, function () {
  47723. loop.executeNext();
  47724. });
  47725. }
  47726. }, function () {
  47727. setTimeout(function () {
  47728. //reconstruct this part of the mesh
  47729. _this.reconstructMesh(submeshIndex);
  47730. successCallback();
  47731. }, 0);
  47732. });
  47733. };
  47734. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  47735. var _this = this;
  47736. this.vertices = [];
  47737. this.triangles = [];
  47738. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47739. var indices = this._mesh.getIndices();
  47740. var submesh = this._mesh.subMeshes[submeshIndex];
  47741. var findInVertices = function (positionToSearch) {
  47742. if (optimizeMesh) {
  47743. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  47744. if (_this.vertices[ii].position.equals(positionToSearch)) {
  47745. return _this.vertices[ii];
  47746. }
  47747. }
  47748. }
  47749. return null;
  47750. };
  47751. var vertexReferences = [];
  47752. var vertexInit = function (i) {
  47753. var offset = i + submesh.verticesStart;
  47754. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  47755. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  47756. vertex.originalOffsets.push(offset);
  47757. if (vertex.id === _this.vertices.length) {
  47758. _this.vertices.push(vertex);
  47759. }
  47760. vertexReferences.push(vertex.id);
  47761. };
  47762. //var totalVertices = mesh.getTotalVertices();
  47763. var totalVertices = submesh.verticesCount;
  47764. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  47765. var indicesInit = function (i) {
  47766. var offset = (submesh.indexStart / 3) + i;
  47767. var pos = (offset * 3);
  47768. var i0 = indices[pos + 0];
  47769. var i1 = indices[pos + 1];
  47770. var i2 = indices[pos + 2];
  47771. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  47772. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  47773. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  47774. var triangle = new DecimationTriangle([v0, v1, v2]);
  47775. triangle.originalOffset = pos;
  47776. _this.triangles.push(triangle);
  47777. };
  47778. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  47779. _this.init(callback);
  47780. });
  47781. });
  47782. };
  47783. QuadraticErrorSimplification.prototype.init = function (callback) {
  47784. var _this = this;
  47785. var triangleInit1 = function (i) {
  47786. var t = _this.triangles[i];
  47787. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  47788. for (var j = 0; j < 3; j++) {
  47789. 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))));
  47790. }
  47791. };
  47792. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  47793. var triangleInit2 = function (i) {
  47794. var t = _this.triangles[i];
  47795. for (var j = 0; j < 3; ++j) {
  47796. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  47797. }
  47798. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  47799. };
  47800. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  47801. _this.initialized = true;
  47802. callback();
  47803. });
  47804. });
  47805. };
  47806. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  47807. var newTriangles = [];
  47808. var i;
  47809. for (i = 0; i < this.vertices.length; ++i) {
  47810. this.vertices[i].triangleCount = 0;
  47811. }
  47812. var t;
  47813. var j;
  47814. for (i = 0; i < this.triangles.length; ++i) {
  47815. if (!this.triangles[i].deleted) {
  47816. t = this.triangles[i];
  47817. for (j = 0; j < 3; ++j) {
  47818. t.vertices[j].triangleCount = 1;
  47819. }
  47820. newTriangles.push(t);
  47821. }
  47822. }
  47823. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  47824. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  47825. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  47826. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  47827. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47828. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47829. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47830. var vertexCount = 0;
  47831. for (i = 0; i < this.vertices.length; ++i) {
  47832. var vertex = this.vertices[i];
  47833. vertex.id = vertexCount;
  47834. if (vertex.triangleCount) {
  47835. vertex.originalOffsets.forEach(function (originalOffset) {
  47836. newPositionData.push(vertex.position.x);
  47837. newPositionData.push(vertex.position.y);
  47838. newPositionData.push(vertex.position.z);
  47839. newNormalData.push(normalData[originalOffset * 3]);
  47840. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  47841. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  47842. if (uvs && uvs.length) {
  47843. newUVsData.push(uvs[(originalOffset * 2)]);
  47844. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  47845. }
  47846. else if (colorsData && colorsData.length) {
  47847. newColorsData.push(colorsData[(originalOffset * 4)]);
  47848. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  47849. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  47850. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  47851. }
  47852. ++vertexCount;
  47853. });
  47854. }
  47855. }
  47856. var startingIndex = this._reconstructedMesh.getTotalIndices();
  47857. var startingVertex = this._reconstructedMesh.getTotalVertices();
  47858. var submeshesArray = this._reconstructedMesh.subMeshes;
  47859. this._reconstructedMesh.subMeshes = [];
  47860. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  47861. var originalIndices = this._mesh.getIndices();
  47862. for (i = 0; i < newTriangles.length; ++i) {
  47863. t = newTriangles[i]; //now get the new referencing point for each vertex
  47864. [0, 1, 2].forEach(function (idx) {
  47865. var id = originalIndices[t.originalOffset + idx];
  47866. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  47867. if (offset < 0)
  47868. offset = 0;
  47869. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  47870. });
  47871. }
  47872. //overwriting the old vertex buffers and indices.
  47873. this._reconstructedMesh.setIndices(newIndicesArray);
  47874. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  47875. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  47876. if (newUVsData.length > 0)
  47877. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  47878. if (newColorsData.length > 0)
  47879. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  47880. //create submesh
  47881. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  47882. if (submeshIndex > 0) {
  47883. this._reconstructedMesh.subMeshes = [];
  47884. submeshesArray.forEach(function (submesh) {
  47885. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  47886. });
  47887. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  47888. }
  47889. };
  47890. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  47891. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  47892. this._reconstructedMesh.material = this._mesh.material;
  47893. this._reconstructedMesh.parent = this._mesh.parent;
  47894. this._reconstructedMesh.isVisible = false;
  47895. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  47896. };
  47897. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  47898. for (var i = 0; i < vertex1.triangleCount; ++i) {
  47899. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  47900. if (t.deleted)
  47901. continue;
  47902. var s = this.references[vertex1.triangleStart + i].vertexId;
  47903. var v1 = t.vertices[(s + 1) % 3];
  47904. var v2 = t.vertices[(s + 2) % 3];
  47905. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  47906. deletedArray[i] = true;
  47907. delTr.push(t);
  47908. continue;
  47909. }
  47910. var d1 = v1.position.subtract(point);
  47911. d1 = d1.normalize();
  47912. var d2 = v2.position.subtract(point);
  47913. d2 = d2.normalize();
  47914. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  47915. return true;
  47916. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  47917. deletedArray[i] = false;
  47918. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  47919. return true;
  47920. }
  47921. return false;
  47922. };
  47923. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  47924. var newDeleted = deletedTriangles;
  47925. for (var i = 0; i < vertex.triangleCount; ++i) {
  47926. var ref = this.references[vertex.triangleStart + i];
  47927. var t = this.triangles[ref.triangleId];
  47928. if (t.deleted)
  47929. continue;
  47930. if (deletedArray[i] && t.deletePending) {
  47931. t.deleted = true;
  47932. newDeleted++;
  47933. continue;
  47934. }
  47935. t.vertices[ref.vertexId] = origVertex;
  47936. t.isDirty = true;
  47937. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  47938. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  47939. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  47940. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  47941. this.references.push(ref);
  47942. }
  47943. return newDeleted;
  47944. };
  47945. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  47946. for (var i = 0; i < this.vertices.length; ++i) {
  47947. var vCount = [];
  47948. var vId = [];
  47949. var v = this.vertices[i];
  47950. var j;
  47951. for (j = 0; j < v.triangleCount; ++j) {
  47952. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  47953. for (var ii = 0; ii < 3; ii++) {
  47954. var ofs = 0;
  47955. var vv = triangle.vertices[ii];
  47956. while (ofs < vCount.length) {
  47957. if (vId[ofs] === vv.id)
  47958. break;
  47959. ++ofs;
  47960. }
  47961. if (ofs === vCount.length) {
  47962. vCount.push(1);
  47963. vId.push(vv.id);
  47964. }
  47965. else {
  47966. vCount[ofs]++;
  47967. }
  47968. }
  47969. }
  47970. for (j = 0; j < vCount.length; ++j) {
  47971. if (vCount[j] === 1) {
  47972. this.vertices[vId[j]].isBorder = true;
  47973. }
  47974. else {
  47975. this.vertices[vId[j]].isBorder = false;
  47976. }
  47977. }
  47978. }
  47979. };
  47980. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  47981. if (identifyBorders === void 0) { identifyBorders = false; }
  47982. var i;
  47983. if (!identifyBorders) {
  47984. var newTrianglesVector = [];
  47985. for (i = 0; i < this.triangles.length; ++i) {
  47986. if (!this.triangles[i].deleted) {
  47987. newTrianglesVector.push(this.triangles[i]);
  47988. }
  47989. }
  47990. this.triangles = newTrianglesVector;
  47991. }
  47992. for (i = 0; i < this.vertices.length; ++i) {
  47993. this.vertices[i].triangleCount = 0;
  47994. this.vertices[i].triangleStart = 0;
  47995. }
  47996. var t;
  47997. var j;
  47998. var v;
  47999. for (i = 0; i < this.triangles.length; ++i) {
  48000. t = this.triangles[i];
  48001. for (j = 0; j < 3; ++j) {
  48002. v = t.vertices[j];
  48003. v.triangleCount++;
  48004. }
  48005. }
  48006. var tStart = 0;
  48007. for (i = 0; i < this.vertices.length; ++i) {
  48008. this.vertices[i].triangleStart = tStart;
  48009. tStart += this.vertices[i].triangleCount;
  48010. this.vertices[i].triangleCount = 0;
  48011. }
  48012. var newReferences = new Array(this.triangles.length * 3);
  48013. for (i = 0; i < this.triangles.length; ++i) {
  48014. t = this.triangles[i];
  48015. for (j = 0; j < 3; ++j) {
  48016. v = t.vertices[j];
  48017. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  48018. v.triangleCount++;
  48019. }
  48020. }
  48021. this.references = newReferences;
  48022. if (identifyBorders) {
  48023. this.identifyBorder();
  48024. }
  48025. };
  48026. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  48027. var x = point.x;
  48028. var y = point.y;
  48029. var z = point.z;
  48030. 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
  48031. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  48032. };
  48033. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  48034. var q = vertex1.q.add(vertex2.q);
  48035. var border = vertex1.isBorder && vertex2.isBorder;
  48036. var error = 0;
  48037. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  48038. if (qDet !== 0 && !border) {
  48039. if (!pointResult) {
  48040. pointResult = BABYLON.Vector3.Zero();
  48041. }
  48042. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  48043. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  48044. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  48045. error = this.vertexError(q, pointResult);
  48046. }
  48047. else {
  48048. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  48049. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  48050. var error1 = this.vertexError(q, vertex1.position);
  48051. var error2 = this.vertexError(q, vertex2.position);
  48052. var error3 = this.vertexError(q, p3);
  48053. error = Math.min(error1, error2, error3);
  48054. if (error === error1) {
  48055. if (pointResult) {
  48056. pointResult.copyFrom(vertex1.position);
  48057. }
  48058. }
  48059. else if (error === error2) {
  48060. if (pointResult) {
  48061. pointResult.copyFrom(vertex2.position);
  48062. }
  48063. }
  48064. else {
  48065. if (pointResult) {
  48066. pointResult.copyFrom(p3);
  48067. }
  48068. }
  48069. }
  48070. return error;
  48071. };
  48072. return QuadraticErrorSimplification;
  48073. }());
  48074. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  48075. })(BABYLON || (BABYLON = {}));
  48076. //# sourceMappingURL=babylon.meshSimplification.js.map
  48077. var BABYLON;
  48078. (function (BABYLON) {
  48079. var serializedGeometries = [];
  48080. var serializeGeometry = function (geometry, serializationGeometries) {
  48081. if (serializedGeometries[geometry.id]) {
  48082. return;
  48083. }
  48084. if (geometry.doNotSerialize) {
  48085. return;
  48086. }
  48087. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  48088. serializationGeometries.boxes.push(geometry.serialize());
  48089. }
  48090. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  48091. serializationGeometries.spheres.push(geometry.serialize());
  48092. }
  48093. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  48094. serializationGeometries.cylinders.push(geometry.serialize());
  48095. }
  48096. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  48097. serializationGeometries.toruses.push(geometry.serialize());
  48098. }
  48099. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  48100. serializationGeometries.grounds.push(geometry.serialize());
  48101. }
  48102. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  48103. serializationGeometries.planes.push(geometry.serialize());
  48104. }
  48105. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  48106. serializationGeometries.torusKnots.push(geometry.serialize());
  48107. }
  48108. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  48109. throw new Error("Unknown primitive type");
  48110. }
  48111. else {
  48112. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  48113. }
  48114. serializedGeometries[geometry.id] = true;
  48115. };
  48116. var serializeMesh = function (mesh, serializationScene) {
  48117. var serializationObject = {};
  48118. // Geometry
  48119. var geometry = mesh._geometry;
  48120. if (geometry) {
  48121. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  48122. // 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
  48123. serializeGeometry(geometry, serializationScene.geometries);
  48124. }
  48125. }
  48126. // Custom
  48127. if (mesh.serialize) {
  48128. mesh.serialize(serializationObject);
  48129. }
  48130. return serializationObject;
  48131. };
  48132. var finalizeSingleMesh = function (mesh, serializationObject) {
  48133. //only works if the mesh is already loaded
  48134. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  48135. //serialize material
  48136. if (mesh.material) {
  48137. if (mesh.material instanceof BABYLON.StandardMaterial) {
  48138. serializationObject.materials = serializationObject.materials || [];
  48139. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  48140. serializationObject.materials.push(mesh.material.serialize());
  48141. }
  48142. }
  48143. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  48144. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  48145. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  48146. serializationObject.multiMaterials.push(mesh.material.serialize());
  48147. }
  48148. }
  48149. }
  48150. //serialize geometry
  48151. var geometry = mesh._geometry;
  48152. if (geometry) {
  48153. if (!serializationObject.geometries) {
  48154. serializationObject.geometries = {};
  48155. serializationObject.geometries.boxes = [];
  48156. serializationObject.geometries.spheres = [];
  48157. serializationObject.geometries.cylinders = [];
  48158. serializationObject.geometries.toruses = [];
  48159. serializationObject.geometries.grounds = [];
  48160. serializationObject.geometries.planes = [];
  48161. serializationObject.geometries.torusKnots = [];
  48162. serializationObject.geometries.vertexData = [];
  48163. }
  48164. serializeGeometry(geometry, serializationObject.geometries);
  48165. }
  48166. // Skeletons
  48167. if (mesh.skeleton) {
  48168. serializationObject.skeletons = serializationObject.skeletons || [];
  48169. serializationObject.skeletons.push(mesh.skeleton.serialize());
  48170. }
  48171. //serialize the actual mesh
  48172. serializationObject.meshes = serializationObject.meshes || [];
  48173. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  48174. }
  48175. };
  48176. var SceneSerializer = (function () {
  48177. function SceneSerializer() {
  48178. }
  48179. SceneSerializer.ClearCache = function () {
  48180. serializedGeometries = [];
  48181. };
  48182. SceneSerializer.Serialize = function (scene) {
  48183. var serializationObject = {};
  48184. SceneSerializer.ClearCache();
  48185. // Scene
  48186. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  48187. serializationObject.autoClear = scene.autoClear;
  48188. serializationObject.clearColor = scene.clearColor.asArray();
  48189. serializationObject.ambientColor = scene.ambientColor.asArray();
  48190. serializationObject.gravity = scene.gravity.asArray();
  48191. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  48192. serializationObject.workerCollisions = scene.workerCollisions;
  48193. // Fog
  48194. if (scene.fogMode && scene.fogMode !== 0) {
  48195. serializationObject.fogMode = scene.fogMode;
  48196. serializationObject.fogColor = scene.fogColor.asArray();
  48197. serializationObject.fogStart = scene.fogStart;
  48198. serializationObject.fogEnd = scene.fogEnd;
  48199. serializationObject.fogDensity = scene.fogDensity;
  48200. }
  48201. //Physics
  48202. if (scene.isPhysicsEnabled()) {
  48203. serializationObject.physicsEnabled = true;
  48204. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  48205. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  48206. }
  48207. // Metadata
  48208. if (scene.metadata) {
  48209. serializationObject.metadata = scene.metadata;
  48210. }
  48211. // Lights
  48212. serializationObject.lights = [];
  48213. var index;
  48214. var light;
  48215. for (index = 0; index < scene.lights.length; index++) {
  48216. light = scene.lights[index];
  48217. if (!light.doNotSerialize) {
  48218. serializationObject.lights.push(light.serialize());
  48219. }
  48220. }
  48221. // Cameras
  48222. serializationObject.cameras = [];
  48223. for (index = 0; index < scene.cameras.length; index++) {
  48224. var camera = scene.cameras[index];
  48225. if (!camera.doNotSerialize) {
  48226. serializationObject.cameras.push(camera.serialize());
  48227. }
  48228. }
  48229. if (scene.activeCamera) {
  48230. serializationObject.activeCameraID = scene.activeCamera.id;
  48231. }
  48232. // Animations
  48233. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  48234. // Materials
  48235. serializationObject.materials = [];
  48236. serializationObject.multiMaterials = [];
  48237. var material;
  48238. for (index = 0; index < scene.materials.length; index++) {
  48239. material = scene.materials[index];
  48240. if (!material.doNotSerialize) {
  48241. serializationObject.materials.push(material.serialize());
  48242. }
  48243. }
  48244. // MultiMaterials
  48245. serializationObject.multiMaterials = [];
  48246. for (index = 0; index < scene.multiMaterials.length; index++) {
  48247. var multiMaterial = scene.multiMaterials[index];
  48248. serializationObject.multiMaterials.push(multiMaterial.serialize());
  48249. }
  48250. // Skeletons
  48251. serializationObject.skeletons = [];
  48252. for (index = 0; index < scene.skeletons.length; index++) {
  48253. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  48254. }
  48255. // Geometries
  48256. serializationObject.geometries = {};
  48257. serializationObject.geometries.boxes = [];
  48258. serializationObject.geometries.spheres = [];
  48259. serializationObject.geometries.cylinders = [];
  48260. serializationObject.geometries.toruses = [];
  48261. serializationObject.geometries.grounds = [];
  48262. serializationObject.geometries.planes = [];
  48263. serializationObject.geometries.torusKnots = [];
  48264. serializationObject.geometries.vertexData = [];
  48265. serializedGeometries = [];
  48266. var geometries = scene.getGeometries();
  48267. for (index = 0; index < geometries.length; index++) {
  48268. var geometry = geometries[index];
  48269. if (geometry.isReady()) {
  48270. serializeGeometry(geometry, serializationObject.geometries);
  48271. }
  48272. }
  48273. // Meshes
  48274. serializationObject.meshes = [];
  48275. for (index = 0; index < scene.meshes.length; index++) {
  48276. var abstractMesh = scene.meshes[index];
  48277. if (abstractMesh instanceof BABYLON.Mesh) {
  48278. var mesh = abstractMesh;
  48279. if (!mesh.doNotSerialize) {
  48280. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  48281. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  48282. }
  48283. }
  48284. }
  48285. }
  48286. // Particles Systems
  48287. serializationObject.particleSystems = [];
  48288. for (index = 0; index < scene.particleSystems.length; index++) {
  48289. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  48290. }
  48291. // Lens flares
  48292. serializationObject.lensFlareSystems = [];
  48293. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  48294. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  48295. }
  48296. // Shadows
  48297. serializationObject.shadowGenerators = [];
  48298. for (index = 0; index < scene.lights.length; index++) {
  48299. light = scene.lights[index];
  48300. var shadowGenerator = light.getShadowGenerator();
  48301. // Only support serialization for official generator so far.
  48302. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  48303. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  48304. }
  48305. }
  48306. // Action Manager
  48307. if (scene.actionManager) {
  48308. serializationObject.actions = scene.actionManager.serialize("scene");
  48309. }
  48310. // Audio
  48311. serializationObject.sounds = [];
  48312. for (index = 0; index < scene.soundTracks.length; index++) {
  48313. var soundtrack = scene.soundTracks[index];
  48314. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  48315. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  48316. }
  48317. }
  48318. return serializationObject;
  48319. };
  48320. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  48321. if (withParents === void 0) { withParents = false; }
  48322. if (withChildren === void 0) { withChildren = false; }
  48323. var serializationObject = {};
  48324. SceneSerializer.ClearCache();
  48325. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  48326. if (withParents || withChildren) {
  48327. //deliberate for loop! not for each, appended should be processed as well.
  48328. for (var i = 0; i < toSerialize.length; ++i) {
  48329. if (withChildren) {
  48330. toSerialize[i].getDescendants().forEach(function (node) {
  48331. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  48332. toSerialize.push(node);
  48333. }
  48334. });
  48335. }
  48336. //make sure the array doesn't contain the object already
  48337. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  48338. toSerialize.push(toSerialize[i].parent);
  48339. }
  48340. }
  48341. }
  48342. toSerialize.forEach(function (mesh) {
  48343. finalizeSingleMesh(mesh, serializationObject);
  48344. });
  48345. return serializationObject;
  48346. };
  48347. return SceneSerializer;
  48348. }());
  48349. BABYLON.SceneSerializer = SceneSerializer;
  48350. })(BABYLON || (BABYLON = {}));
  48351. //# sourceMappingURL=babylon.sceneSerializer.js.map
  48352. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  48353. // Huge respect for a such great lib.
  48354. // Earcut license:
  48355. // Copyright (c) 2016, Mapbox
  48356. //
  48357. // Permission to use, copy, modify, and/or distribute this software for any purpose
  48358. // with or without fee is hereby granted, provided that the above copyright notice
  48359. // and this permission notice appear in all copies.
  48360. //
  48361. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  48362. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  48363. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  48364. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  48365. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  48366. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  48367. // THIS SOFTWARE.
  48368. var Earcut;
  48369. (function (Earcut) {
  48370. /**
  48371. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  48372. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  48373. * @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).
  48374. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  48375. */
  48376. function earcut(data, holeIndices, dim) {
  48377. dim = dim || 2;
  48378. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  48379. if (!outerNode)
  48380. return triangles;
  48381. var minX, minY, maxX, maxY, x, y, size;
  48382. if (hasHoles)
  48383. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  48384. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  48385. if (data.length > 80 * dim) {
  48386. minX = maxX = data[0];
  48387. minY = maxY = data[1];
  48388. for (var i = dim; i < outerLen; i += dim) {
  48389. x = data[i];
  48390. y = data[i + 1];
  48391. if (x < minX)
  48392. minX = x;
  48393. if (y < minY)
  48394. minY = y;
  48395. if (x > maxX)
  48396. maxX = x;
  48397. if (y > maxY)
  48398. maxY = y;
  48399. }
  48400. // minX, minY and size are later used to transform coords into integers for z-order calculation
  48401. size = Math.max(maxX - minX, maxY - minY);
  48402. }
  48403. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  48404. return triangles;
  48405. }
  48406. Earcut.earcut = earcut;
  48407. // create a circular doubly linked list from polygon points in the specified winding order
  48408. function linkedList(data, start, end, dim, clockwise) {
  48409. var i, last;
  48410. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  48411. for (i = start; i < end; i += dim)
  48412. last = insertNode(i, data[i], data[i + 1], last);
  48413. }
  48414. else {
  48415. for (i = end - dim; i >= start; i -= dim)
  48416. last = insertNode(i, data[i], data[i + 1], last);
  48417. }
  48418. if (last && equals(last, last.next)) {
  48419. removeNode(last);
  48420. last = last.next;
  48421. }
  48422. return last;
  48423. }
  48424. // eliminate colinear or duplicate points
  48425. function filterPoints(start, end) {
  48426. if (!start)
  48427. return start;
  48428. if (!end)
  48429. end = start;
  48430. var p = start, again;
  48431. do {
  48432. again = false;
  48433. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  48434. removeNode(p);
  48435. p = end = p.prev;
  48436. if (p === p.next)
  48437. return null;
  48438. again = true;
  48439. }
  48440. else {
  48441. p = p.next;
  48442. }
  48443. } while (again || p !== end);
  48444. return end;
  48445. }
  48446. // main ear slicing loop which triangulates a polygon (given as a linked list)
  48447. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  48448. if (!ear)
  48449. return;
  48450. // interlink polygon nodes in z-order
  48451. if (!pass && size)
  48452. indexCurve(ear, minX, minY, size);
  48453. var stop = ear, prev, next;
  48454. // iterate through ears, slicing them one by one
  48455. while (ear.prev !== ear.next) {
  48456. prev = ear.prev;
  48457. next = ear.next;
  48458. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  48459. // cut off the triangle
  48460. triangles.push(prev.i / dim);
  48461. triangles.push(ear.i / dim);
  48462. triangles.push(next.i / dim);
  48463. removeNode(ear);
  48464. // skipping the next vertice leads to less sliver triangles
  48465. ear = next.next;
  48466. stop = next.next;
  48467. continue;
  48468. }
  48469. ear = next;
  48470. // if we looped through the whole remaining polygon and can't find any more ears
  48471. if (ear === stop) {
  48472. // try filtering points and slicing again
  48473. if (!pass) {
  48474. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  48475. // if this didn't work, try curing all small self-intersections locally
  48476. }
  48477. else if (pass === 1) {
  48478. ear = cureLocalIntersections(ear, triangles, dim);
  48479. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  48480. // as a last resort, try splitting the remaining polygon into two
  48481. }
  48482. else if (pass === 2) {
  48483. splitEarcut(ear, triangles, dim, minX, minY, size);
  48484. }
  48485. break;
  48486. }
  48487. }
  48488. }
  48489. // check whether a polygon node forms a valid ear with adjacent nodes
  48490. function isEar(ear) {
  48491. var a = ear.prev, b = ear, c = ear.next;
  48492. if (area(a, b, c) >= 0)
  48493. return false; // reflex, can't be an ear
  48494. // now make sure we don't have other points inside the potential ear
  48495. var p = ear.next.next;
  48496. while (p !== ear.prev) {
  48497. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  48498. area(p.prev, p, p.next) >= 0)
  48499. return false;
  48500. p = p.next;
  48501. }
  48502. return true;
  48503. }
  48504. function isEarHashed(ear, minX, minY, size) {
  48505. var a = ear.prev, b = ear, c = ear.next;
  48506. if (area(a, b, c) >= 0)
  48507. return false; // reflex, can't be an ear
  48508. // triangle bbox; min & max are calculated like this for speed
  48509. 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);
  48510. // z-order range for the current triangle bbox;
  48511. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  48512. // first look for points inside the triangle in increasing z-order
  48513. var p = ear.nextZ;
  48514. while (p && p.z <= maxZ) {
  48515. if (p !== ear.prev &&
  48516. p !== ear.next &&
  48517. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  48518. area(p.prev, p, p.next) >= 0)
  48519. return false;
  48520. p = p.nextZ;
  48521. }
  48522. // then look for points in decreasing z-order
  48523. p = ear.prevZ;
  48524. while (p && p.z >= minZ) {
  48525. if (p !== ear.prev &&
  48526. p !== ear.next &&
  48527. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  48528. area(p.prev, p, p.next) >= 0)
  48529. return false;
  48530. p = p.prevZ;
  48531. }
  48532. return true;
  48533. }
  48534. // go through all polygon nodes and cure small local self-intersections
  48535. function cureLocalIntersections(start, triangles, dim) {
  48536. var p = start;
  48537. do {
  48538. var a = p.prev, b = p.next.next;
  48539. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  48540. triangles.push(a.i / dim);
  48541. triangles.push(p.i / dim);
  48542. triangles.push(b.i / dim);
  48543. // remove two nodes involved
  48544. removeNode(p);
  48545. removeNode(p.next);
  48546. p = start = b;
  48547. }
  48548. p = p.next;
  48549. } while (p !== start);
  48550. return p;
  48551. }
  48552. // try splitting polygon into two and triangulate them independently
  48553. function splitEarcut(start, triangles, dim, minX, minY, size) {
  48554. // look for a valid diagonal that divides the polygon into two
  48555. var a = start;
  48556. do {
  48557. var b = a.next.next;
  48558. while (b !== a.prev) {
  48559. if (a.i !== b.i && isValidDiagonal(a, b)) {
  48560. // split the polygon in two by the diagonal
  48561. var c = splitPolygon(a, b);
  48562. // filter colinear points around the cuts
  48563. a = filterPoints(a, a.next);
  48564. c = filterPoints(c, c.next);
  48565. // run earcut on each half
  48566. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  48567. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  48568. return;
  48569. }
  48570. b = b.next;
  48571. }
  48572. a = a.next;
  48573. } while (a !== start);
  48574. }
  48575. // link every hole into the outer loop, producing a single-ring polygon without holes
  48576. function eliminateHoles(data, holeIndices, outerNode, dim) {
  48577. var queue = [], i, len, start, end, list;
  48578. for (i = 0, len = holeIndices.length; i < len; i++) {
  48579. start = holeIndices[i] * dim;
  48580. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  48581. list = linkedList(data, start, end, dim, false);
  48582. if (list === list.next)
  48583. list.steiner = true;
  48584. queue.push(getLeftmost(list));
  48585. }
  48586. queue.sort(compareX);
  48587. // process holes from left to right
  48588. for (i = 0; i < queue.length; i++) {
  48589. eliminateHole(queue[i], outerNode);
  48590. outerNode = filterPoints(outerNode, outerNode.next);
  48591. }
  48592. return outerNode;
  48593. }
  48594. function compareX(a, b) {
  48595. return a.x - b.x;
  48596. }
  48597. // find a bridge between vertices that connects hole with an outer ring and and link it
  48598. function eliminateHole(hole, outerNode) {
  48599. outerNode = findHoleBridge(hole, outerNode);
  48600. if (outerNode) {
  48601. var b = splitPolygon(outerNode, hole);
  48602. filterPoints(b, b.next);
  48603. }
  48604. }
  48605. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  48606. function findHoleBridge(hole, outerNode) {
  48607. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  48608. // find a segment intersected by a ray from the hole's leftmost point to the left;
  48609. // segment's endpoint with lesser x will be potential connection point
  48610. do {
  48611. if (hy <= p.y && hy >= p.next.y) {
  48612. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  48613. if (x <= hx && x > qx) {
  48614. qx = x;
  48615. if (x === hx) {
  48616. if (hy === p.y)
  48617. return p;
  48618. if (hy === p.next.y)
  48619. return p.next;
  48620. }
  48621. m = p.x < p.next.x ? p : p.next;
  48622. }
  48623. }
  48624. p = p.next;
  48625. } while (p !== outerNode);
  48626. if (!m)
  48627. return null;
  48628. if (hx === qx)
  48629. return m.prev; // hole touches outer segment; pick lower endpoint
  48630. // look for points inside the triangle of hole point, segment intersection and endpoint;
  48631. // if there are no points found, we have a valid connection;
  48632. // otherwise choose the point of the minimum angle with the ray as connection point
  48633. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  48634. p = m.next;
  48635. while (p !== stop) {
  48636. if (hx >= p.x &&
  48637. p.x >= mx &&
  48638. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  48639. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  48640. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  48641. m = p;
  48642. tanMin = tan;
  48643. }
  48644. }
  48645. p = p.next;
  48646. }
  48647. return m;
  48648. }
  48649. // interlink polygon nodes in z-order
  48650. function indexCurve(start, minX, minY, size) {
  48651. var p = start;
  48652. do {
  48653. if (p.z === null)
  48654. p.z = zOrder(p.x, p.y, minX, minY, size);
  48655. p.prevZ = p.prev;
  48656. p.nextZ = p.next;
  48657. p = p.next;
  48658. } while (p !== start);
  48659. p.prevZ.nextZ = null;
  48660. p.prevZ = null;
  48661. sortLinked(p);
  48662. }
  48663. // Simon Tatham's linked list merge sort algorithm
  48664. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  48665. function sortLinked(list) {
  48666. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  48667. do {
  48668. p = list;
  48669. list = null;
  48670. tail = null;
  48671. numMerges = 0;
  48672. while (p) {
  48673. numMerges++;
  48674. q = p;
  48675. pSize = 0;
  48676. for (i = 0; i < inSize; i++) {
  48677. pSize++;
  48678. q = q.nextZ;
  48679. if (!q)
  48680. break;
  48681. }
  48682. qSize = inSize;
  48683. while (pSize > 0 || (qSize > 0 && q)) {
  48684. if (pSize === 0) {
  48685. e = q;
  48686. q = q.nextZ;
  48687. qSize--;
  48688. }
  48689. else if (qSize === 0 || !q) {
  48690. e = p;
  48691. p = p.nextZ;
  48692. pSize--;
  48693. }
  48694. else if (p.z <= q.z) {
  48695. e = p;
  48696. p = p.nextZ;
  48697. pSize--;
  48698. }
  48699. else {
  48700. e = q;
  48701. q = q.nextZ;
  48702. qSize--;
  48703. }
  48704. if (tail)
  48705. tail.nextZ = e;
  48706. else
  48707. list = e;
  48708. e.prevZ = tail;
  48709. tail = e;
  48710. }
  48711. p = q;
  48712. }
  48713. tail.nextZ = null;
  48714. inSize *= 2;
  48715. } while (numMerges > 1);
  48716. return list;
  48717. }
  48718. // z-order of a point given coords and size of the data bounding box
  48719. function zOrder(x, y, minX, minY, size) {
  48720. // coords are transformed into non-negative 15-bit integer range
  48721. x = 32767 * (x - minX) / size;
  48722. y = 32767 * (y - minY) / size;
  48723. x = (x | (x << 8)) & 0x00FF00FF;
  48724. x = (x | (x << 4)) & 0x0F0F0F0F;
  48725. x = (x | (x << 2)) & 0x33333333;
  48726. x = (x | (x << 1)) & 0x55555555;
  48727. y = (y | (y << 8)) & 0x00FF00FF;
  48728. y = (y | (y << 4)) & 0x0F0F0F0F;
  48729. y = (y | (y << 2)) & 0x33333333;
  48730. y = (y | (y << 1)) & 0x55555555;
  48731. return x | (y << 1);
  48732. }
  48733. // find the leftmost node of a polygon ring
  48734. function getLeftmost(start) {
  48735. var p = start, leftmost = start;
  48736. do {
  48737. if (p.x < leftmost.x)
  48738. leftmost = p;
  48739. p = p.next;
  48740. } while (p !== start);
  48741. return leftmost;
  48742. }
  48743. // check if a point lies within a convex triangle
  48744. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  48745. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  48746. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  48747. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  48748. }
  48749. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  48750. function isValidDiagonal(a, b) {
  48751. return a.next.i !== b.i &&
  48752. a.prev.i !== b.i &&
  48753. !intersectsPolygon(a, b) &&
  48754. locallyInside(a, b) &&
  48755. locallyInside(b, a) &&
  48756. middleInside(a, b);
  48757. }
  48758. // signed area of a triangle
  48759. function area(p, q, r) {
  48760. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  48761. }
  48762. // check if two points are equal
  48763. function equals(p1, p2) {
  48764. return p1.x === p2.x && p1.y === p2.y;
  48765. }
  48766. // check if two segments intersect
  48767. function intersects(p1, q1, p2, q2) {
  48768. if ((equals(p1, q1) && equals(p2, q2)) ||
  48769. (equals(p1, q2) && equals(p2, q1)))
  48770. return true;
  48771. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  48772. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  48773. }
  48774. // check if a polygon diagonal intersects any polygon segments
  48775. function intersectsPolygon(a, b) {
  48776. var p = a;
  48777. do {
  48778. if (p.i !== a.i &&
  48779. p.next.i !== a.i &&
  48780. p.i !== b.i &&
  48781. p.next.i !== b.i &&
  48782. intersects(p, p.next, a, b))
  48783. return true;
  48784. p = p.next;
  48785. } while (p !== a);
  48786. return false;
  48787. }
  48788. // check if a polygon diagonal is locally inside the polygon
  48789. function locallyInside(a, b) {
  48790. return area(a.prev, a, a.next) < 0
  48791. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  48792. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  48793. }
  48794. // check if the middle point of a polygon diagonal is inside the polygon
  48795. function middleInside(a, b) {
  48796. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  48797. do {
  48798. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  48799. inside = !inside;
  48800. p = p.next;
  48801. } while (p !== a);
  48802. return inside;
  48803. }
  48804. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  48805. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  48806. function splitPolygon(a, b) {
  48807. 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;
  48808. a.next = b;
  48809. b.prev = a;
  48810. a2.next = an;
  48811. an.prev = a2;
  48812. b2.next = a2;
  48813. a2.prev = b2;
  48814. bp.next = b2;
  48815. b2.prev = bp;
  48816. return b2;
  48817. }
  48818. // create a node and optionally link it with previous one (in a circular doubly linked list)
  48819. function insertNode(i, x, y, last) {
  48820. var p = new Node(i, x, y);
  48821. if (!last) {
  48822. p.prev = p;
  48823. p.next = p;
  48824. }
  48825. else {
  48826. p.next = last.next;
  48827. p.prev = last;
  48828. last.next.prev = p;
  48829. last.next = p;
  48830. }
  48831. return p;
  48832. }
  48833. function removeNode(p) {
  48834. p.next.prev = p.prev;
  48835. p.prev.next = p.next;
  48836. if (p.prevZ)
  48837. p.prevZ.nextZ = p.nextZ;
  48838. if (p.nextZ)
  48839. p.nextZ.prevZ = p.prevZ;
  48840. }
  48841. function Node(i, x, y) {
  48842. // vertice index in coordinates array
  48843. this.i = i;
  48844. // vertex coordinates
  48845. this.x = x;
  48846. this.y = y;
  48847. // previous and next vertice nodes in a polygon ring
  48848. this.prev = null;
  48849. this.next = null;
  48850. // z-order curve value
  48851. this.z = null;
  48852. // previous and next nodes in z-order
  48853. this.prevZ = null;
  48854. this.nextZ = null;
  48855. // indicates whether this is a steiner point
  48856. this.steiner = false;
  48857. }
  48858. /**
  48859. * return a percentage difference between the polygon area and its triangulation area;
  48860. * used to verify correctness of triangulation
  48861. */
  48862. function deviation(data, holeIndices, dim, triangles) {
  48863. var hasHoles = holeIndices && holeIndices.length;
  48864. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  48865. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  48866. if (hasHoles) {
  48867. for (var i = 0, len = holeIndices.length; i < len; i++) {
  48868. var start = holeIndices[i] * dim;
  48869. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  48870. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  48871. }
  48872. }
  48873. var trianglesArea = 0;
  48874. for (i = 0; i < triangles.length; i += 3) {
  48875. var a = triangles[i] * dim;
  48876. var b = triangles[i + 1] * dim;
  48877. var c = triangles[i + 2] * dim;
  48878. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  48879. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  48880. }
  48881. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  48882. }
  48883. Earcut.deviation = deviation;
  48884. ;
  48885. function signedArea(data, start, end, dim) {
  48886. var sum = 0;
  48887. for (var i = start, j = end - dim; i < end; i += dim) {
  48888. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  48889. j = i;
  48890. }
  48891. return sum;
  48892. }
  48893. /**
  48894. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  48895. */
  48896. function flatten(data) {
  48897. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  48898. for (var i = 0; i < data.length; i++) {
  48899. for (var j = 0; j < data[i].length; j++) {
  48900. for (var d = 0; d < dim; d++)
  48901. result.vertices.push(data[i][j][d]);
  48902. }
  48903. if (i > 0) {
  48904. holeIndex += data[i - 1].length;
  48905. result.holes.push(holeIndex);
  48906. }
  48907. }
  48908. return result;
  48909. }
  48910. Earcut.flatten = flatten;
  48911. ;
  48912. })(Earcut || (Earcut = {}));
  48913. //# sourceMappingURL=babylon.earcut.js.map
  48914. var BABYLON;
  48915. (function (BABYLON) {
  48916. // Unique ID when we import meshes from Babylon to CSG
  48917. var currentCSGMeshId = 0;
  48918. // # class Vertex
  48919. // Represents a vertex of a polygon. Use your own vertex class instead of this
  48920. // one to provide additional features like texture coordinates and vertex
  48921. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  48922. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  48923. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  48924. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  48925. // is not used anywhere else.
  48926. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  48927. var Vertex = (function () {
  48928. function Vertex(pos, normal, uv) {
  48929. this.pos = pos;
  48930. this.normal = normal;
  48931. this.uv = uv;
  48932. }
  48933. Vertex.prototype.clone = function () {
  48934. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  48935. };
  48936. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  48937. // orientation of a polygon is flipped.
  48938. Vertex.prototype.flip = function () {
  48939. this.normal = this.normal.scale(-1);
  48940. };
  48941. // Create a new vertex between this vertex and `other` by linearly
  48942. // interpolating all properties using a parameter of `t`. Subclasses should
  48943. // override this to interpolate additional properties.
  48944. Vertex.prototype.interpolate = function (other, t) {
  48945. 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));
  48946. };
  48947. return Vertex;
  48948. }());
  48949. // # class Plane
  48950. // Represents a plane in 3D space.
  48951. var Plane = (function () {
  48952. function Plane(normal, w) {
  48953. this.normal = normal;
  48954. this.w = w;
  48955. }
  48956. Plane.FromPoints = function (a, b, c) {
  48957. var v0 = c.subtract(a);
  48958. var v1 = b.subtract(a);
  48959. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  48960. return null;
  48961. }
  48962. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  48963. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  48964. };
  48965. Plane.prototype.clone = function () {
  48966. return new Plane(this.normal.clone(), this.w);
  48967. };
  48968. Plane.prototype.flip = function () {
  48969. this.normal.scaleInPlace(-1);
  48970. this.w = -this.w;
  48971. };
  48972. // Split `polygon` by this plane if needed, then put the polygon or polygon
  48973. // fragments in the appropriate lists. Coplanar polygons go into either
  48974. // `coplanarFront` or `coplanarBack` depending on their orientation with
  48975. // respect to this plane. Polygons in front or in back of this plane go into
  48976. // either `front` or `back`.
  48977. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  48978. var COPLANAR = 0;
  48979. var FRONT = 1;
  48980. var BACK = 2;
  48981. var SPANNING = 3;
  48982. // Classify each point as well as the entire polygon into one of the above
  48983. // four classes.
  48984. var polygonType = 0;
  48985. var types = [];
  48986. var i;
  48987. var t;
  48988. for (i = 0; i < polygon.vertices.length; i++) {
  48989. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  48990. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  48991. polygonType |= type;
  48992. types.push(type);
  48993. }
  48994. // Put the polygon in the correct list, splitting it when necessary.
  48995. switch (polygonType) {
  48996. case COPLANAR:
  48997. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  48998. break;
  48999. case FRONT:
  49000. front.push(polygon);
  49001. break;
  49002. case BACK:
  49003. back.push(polygon);
  49004. break;
  49005. case SPANNING:
  49006. var f = [], b = [];
  49007. for (i = 0; i < polygon.vertices.length; i++) {
  49008. var j = (i + 1) % polygon.vertices.length;
  49009. var ti = types[i], tj = types[j];
  49010. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  49011. if (ti !== BACK)
  49012. f.push(vi);
  49013. if (ti !== FRONT)
  49014. b.push(ti !== BACK ? vi.clone() : vi);
  49015. if ((ti | tj) === SPANNING) {
  49016. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  49017. var v = vi.interpolate(vj, t);
  49018. f.push(v);
  49019. b.push(v.clone());
  49020. }
  49021. }
  49022. var poly;
  49023. if (f.length >= 3) {
  49024. poly = new Polygon(f, polygon.shared);
  49025. if (poly.plane)
  49026. front.push(poly);
  49027. }
  49028. if (b.length >= 3) {
  49029. poly = new Polygon(b, polygon.shared);
  49030. if (poly.plane)
  49031. back.push(poly);
  49032. }
  49033. break;
  49034. }
  49035. };
  49036. return Plane;
  49037. }());
  49038. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  49039. // point is on the plane.
  49040. Plane.EPSILON = 1e-5;
  49041. // # class Polygon
  49042. // Represents a convex polygon. The vertices used to initialize a polygon must
  49043. // be coplanar and form a convex loop.
  49044. //
  49045. // Each convex polygon has a `shared` property, which is shared between all
  49046. // polygons that are clones of each other or were split from the same polygon.
  49047. // This can be used to define per-polygon properties (such as surface color).
  49048. var Polygon = (function () {
  49049. function Polygon(vertices, shared) {
  49050. this.vertices = vertices;
  49051. this.shared = shared;
  49052. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  49053. }
  49054. Polygon.prototype.clone = function () {
  49055. var vertices = this.vertices.map(function (v) { return v.clone(); });
  49056. return new Polygon(vertices, this.shared);
  49057. };
  49058. Polygon.prototype.flip = function () {
  49059. this.vertices.reverse().map(function (v) { v.flip(); });
  49060. this.plane.flip();
  49061. };
  49062. return Polygon;
  49063. }());
  49064. // # class Node
  49065. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  49066. // by picking a polygon to split along. That polygon (and all other coplanar
  49067. // polygons) are added directly to that node and the other polygons are added to
  49068. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  49069. // no distinction between internal and leaf nodes.
  49070. var Node = (function () {
  49071. function Node(polygons) {
  49072. this.plane = null;
  49073. this.front = null;
  49074. this.back = null;
  49075. this.polygons = [];
  49076. if (polygons) {
  49077. this.build(polygons);
  49078. }
  49079. }
  49080. Node.prototype.clone = function () {
  49081. var node = new Node();
  49082. node.plane = this.plane && this.plane.clone();
  49083. node.front = this.front && this.front.clone();
  49084. node.back = this.back && this.back.clone();
  49085. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  49086. return node;
  49087. };
  49088. // Convert solid space to empty space and empty space to solid space.
  49089. Node.prototype.invert = function () {
  49090. for (var i = 0; i < this.polygons.length; i++) {
  49091. this.polygons[i].flip();
  49092. }
  49093. if (this.plane) {
  49094. this.plane.flip();
  49095. }
  49096. if (this.front) {
  49097. this.front.invert();
  49098. }
  49099. if (this.back) {
  49100. this.back.invert();
  49101. }
  49102. var temp = this.front;
  49103. this.front = this.back;
  49104. this.back = temp;
  49105. };
  49106. // Recursively remove all polygons in `polygons` that are inside this BSP
  49107. // tree.
  49108. Node.prototype.clipPolygons = function (polygons) {
  49109. if (!this.plane)
  49110. return polygons.slice();
  49111. var front = [], back = [];
  49112. for (var i = 0; i < polygons.length; i++) {
  49113. this.plane.splitPolygon(polygons[i], front, back, front, back);
  49114. }
  49115. if (this.front) {
  49116. front = this.front.clipPolygons(front);
  49117. }
  49118. if (this.back) {
  49119. back = this.back.clipPolygons(back);
  49120. }
  49121. else {
  49122. back = [];
  49123. }
  49124. return front.concat(back);
  49125. };
  49126. // Remove all polygons in this BSP tree that are inside the other BSP tree
  49127. // `bsp`.
  49128. Node.prototype.clipTo = function (bsp) {
  49129. this.polygons = bsp.clipPolygons(this.polygons);
  49130. if (this.front)
  49131. this.front.clipTo(bsp);
  49132. if (this.back)
  49133. this.back.clipTo(bsp);
  49134. };
  49135. // Return a list of all polygons in this BSP tree.
  49136. Node.prototype.allPolygons = function () {
  49137. var polygons = this.polygons.slice();
  49138. if (this.front)
  49139. polygons = polygons.concat(this.front.allPolygons());
  49140. if (this.back)
  49141. polygons = polygons.concat(this.back.allPolygons());
  49142. return polygons;
  49143. };
  49144. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  49145. // new polygons are filtered down to the bottom of the tree and become new
  49146. // nodes there. Each set of polygons is partitioned using the first polygon
  49147. // (no heuristic is used to pick a good split).
  49148. Node.prototype.build = function (polygons) {
  49149. if (!polygons.length)
  49150. return;
  49151. if (!this.plane)
  49152. this.plane = polygons[0].plane.clone();
  49153. var front = [], back = [];
  49154. for (var i = 0; i < polygons.length; i++) {
  49155. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  49156. }
  49157. if (front.length) {
  49158. if (!this.front)
  49159. this.front = new Node();
  49160. this.front.build(front);
  49161. }
  49162. if (back.length) {
  49163. if (!this.back)
  49164. this.back = new Node();
  49165. this.back.build(back);
  49166. }
  49167. };
  49168. return Node;
  49169. }());
  49170. var CSG = (function () {
  49171. function CSG() {
  49172. this.polygons = new Array();
  49173. }
  49174. // Convert BABYLON.Mesh to BABYLON.CSG
  49175. CSG.FromMesh = function (mesh) {
  49176. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  49177. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  49178. if (mesh instanceof BABYLON.Mesh) {
  49179. mesh.computeWorldMatrix(true);
  49180. matrix = mesh.getWorldMatrix();
  49181. meshPosition = mesh.position.clone();
  49182. meshRotation = mesh.rotation.clone();
  49183. if (mesh.rotationQuaternion) {
  49184. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  49185. }
  49186. meshScaling = mesh.scaling.clone();
  49187. }
  49188. else {
  49189. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  49190. }
  49191. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49192. var subMeshes = mesh.subMeshes;
  49193. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  49194. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  49195. vertices = [];
  49196. for (var j = 0; j < 3; j++) {
  49197. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  49198. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  49199. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  49200. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  49201. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  49202. vertex = new Vertex(position, normal, uv);
  49203. vertices.push(vertex);
  49204. }
  49205. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  49206. // To handle the case of degenerated triangle
  49207. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  49208. if (polygon.plane)
  49209. polygons.push(polygon);
  49210. }
  49211. }
  49212. var csg = CSG.FromPolygons(polygons);
  49213. csg.matrix = matrix;
  49214. csg.position = meshPosition;
  49215. csg.rotation = meshRotation;
  49216. csg.scaling = meshScaling;
  49217. csg.rotationQuaternion = meshRotationQuaternion;
  49218. currentCSGMeshId++;
  49219. return csg;
  49220. };
  49221. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  49222. CSG.FromPolygons = function (polygons) {
  49223. var csg = new CSG();
  49224. csg.polygons = polygons;
  49225. return csg;
  49226. };
  49227. CSG.prototype.clone = function () {
  49228. var csg = new CSG();
  49229. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  49230. csg.copyTransformAttributes(this);
  49231. return csg;
  49232. };
  49233. CSG.prototype.toPolygons = function () {
  49234. return this.polygons;
  49235. };
  49236. CSG.prototype.union = function (csg) {
  49237. var a = new Node(this.clone().polygons);
  49238. var b = new Node(csg.clone().polygons);
  49239. a.clipTo(b);
  49240. b.clipTo(a);
  49241. b.invert();
  49242. b.clipTo(a);
  49243. b.invert();
  49244. a.build(b.allPolygons());
  49245. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  49246. };
  49247. CSG.prototype.unionInPlace = function (csg) {
  49248. var a = new Node(this.polygons);
  49249. var b = new Node(csg.polygons);
  49250. a.clipTo(b);
  49251. b.clipTo(a);
  49252. b.invert();
  49253. b.clipTo(a);
  49254. b.invert();
  49255. a.build(b.allPolygons());
  49256. this.polygons = a.allPolygons();
  49257. };
  49258. CSG.prototype.subtract = function (csg) {
  49259. var a = new Node(this.clone().polygons);
  49260. var b = new Node(csg.clone().polygons);
  49261. a.invert();
  49262. a.clipTo(b);
  49263. b.clipTo(a);
  49264. b.invert();
  49265. b.clipTo(a);
  49266. b.invert();
  49267. a.build(b.allPolygons());
  49268. a.invert();
  49269. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  49270. };
  49271. CSG.prototype.subtractInPlace = function (csg) {
  49272. var a = new Node(this.polygons);
  49273. var b = new Node(csg.polygons);
  49274. a.invert();
  49275. a.clipTo(b);
  49276. b.clipTo(a);
  49277. b.invert();
  49278. b.clipTo(a);
  49279. b.invert();
  49280. a.build(b.allPolygons());
  49281. a.invert();
  49282. this.polygons = a.allPolygons();
  49283. };
  49284. CSG.prototype.intersect = function (csg) {
  49285. var a = new Node(this.clone().polygons);
  49286. var b = new Node(csg.clone().polygons);
  49287. a.invert();
  49288. b.clipTo(a);
  49289. b.invert();
  49290. a.clipTo(b);
  49291. b.clipTo(a);
  49292. a.build(b.allPolygons());
  49293. a.invert();
  49294. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  49295. };
  49296. CSG.prototype.intersectInPlace = function (csg) {
  49297. var a = new Node(this.polygons);
  49298. var b = new Node(csg.polygons);
  49299. a.invert();
  49300. b.clipTo(a);
  49301. b.invert();
  49302. a.clipTo(b);
  49303. b.clipTo(a);
  49304. a.build(b.allPolygons());
  49305. a.invert();
  49306. this.polygons = a.allPolygons();
  49307. };
  49308. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  49309. // not modified.
  49310. CSG.prototype.inverse = function () {
  49311. var csg = this.clone();
  49312. csg.inverseInPlace();
  49313. return csg;
  49314. };
  49315. CSG.prototype.inverseInPlace = function () {
  49316. this.polygons.map(function (p) { p.flip(); });
  49317. };
  49318. // This is used to keep meshes transformations so they can be restored
  49319. // when we build back a Babylon Mesh
  49320. // NB : All CSG operations are performed in world coordinates
  49321. CSG.prototype.copyTransformAttributes = function (csg) {
  49322. this.matrix = csg.matrix;
  49323. this.position = csg.position;
  49324. this.rotation = csg.rotation;
  49325. this.scaling = csg.scaling;
  49326. this.rotationQuaternion = csg.rotationQuaternion;
  49327. return this;
  49328. };
  49329. // Build Raw mesh from CSG
  49330. // Coordinates here are in world space
  49331. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  49332. var matrix = this.matrix.clone();
  49333. matrix.invert();
  49334. 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;
  49335. if (keepSubMeshes) {
  49336. // Sort Polygons, since subMeshes are indices range
  49337. polygons.sort(function (a, b) {
  49338. if (a.shared.meshId === b.shared.meshId) {
  49339. return a.shared.subMeshId - b.shared.subMeshId;
  49340. }
  49341. else {
  49342. return a.shared.meshId - b.shared.meshId;
  49343. }
  49344. });
  49345. }
  49346. for (var i = 0, il = polygons.length; i < il; i++) {
  49347. polygon = polygons[i];
  49348. // Building SubMeshes
  49349. if (!subMesh_dict[polygon.shared.meshId]) {
  49350. subMesh_dict[polygon.shared.meshId] = {};
  49351. }
  49352. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  49353. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  49354. indexStart: +Infinity,
  49355. indexEnd: -Infinity,
  49356. materialIndex: polygon.shared.materialIndex
  49357. };
  49358. }
  49359. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  49360. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  49361. polygonIndices[0] = 0;
  49362. polygonIndices[1] = j - 1;
  49363. polygonIndices[2] = j;
  49364. for (var k = 0; k < 3; k++) {
  49365. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  49366. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  49367. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  49368. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  49369. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  49370. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  49371. // Check if 2 points can be merged
  49372. if (!(typeof vertex_idx !== 'undefined' &&
  49373. normals[vertex_idx * 3] === localNormal.x &&
  49374. normals[vertex_idx * 3 + 1] === localNormal.y &&
  49375. normals[vertex_idx * 3 + 2] === localNormal.z &&
  49376. uvs[vertex_idx * 2] === uv.x &&
  49377. uvs[vertex_idx * 2 + 1] === uv.y)) {
  49378. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  49379. uvs.push(uv.x, uv.y);
  49380. normals.push(normal.x, normal.y, normal.z);
  49381. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  49382. }
  49383. indices.push(vertex_idx);
  49384. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  49385. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  49386. currentIndex++;
  49387. }
  49388. }
  49389. }
  49390. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  49391. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  49392. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  49393. mesh.setIndices(indices);
  49394. if (keepSubMeshes) {
  49395. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  49396. var materialIndexOffset = 0, materialMaxIndex;
  49397. mesh.subMeshes = new Array();
  49398. for (var m in subMesh_dict) {
  49399. materialMaxIndex = -1;
  49400. for (var sm in subMesh_dict[m]) {
  49401. subMesh_obj = subMesh_dict[m][sm];
  49402. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  49403. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  49404. }
  49405. materialIndexOffset += ++materialMaxIndex;
  49406. }
  49407. }
  49408. return mesh;
  49409. };
  49410. // Build Mesh from CSG taking material and transforms into account
  49411. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  49412. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  49413. mesh.material = material;
  49414. mesh.position.copyFrom(this.position);
  49415. mesh.rotation.copyFrom(this.rotation);
  49416. if (this.rotationQuaternion) {
  49417. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  49418. }
  49419. mesh.scaling.copyFrom(this.scaling);
  49420. mesh.computeWorldMatrix(true);
  49421. return mesh;
  49422. };
  49423. return CSG;
  49424. }());
  49425. BABYLON.CSG = CSG;
  49426. })(BABYLON || (BABYLON = {}));
  49427. //# sourceMappingURL=babylon.csg.js.map
  49428. var BABYLON;
  49429. (function (BABYLON) {
  49430. var VRDistortionCorrectionPostProcess = (function (_super) {
  49431. __extends(VRDistortionCorrectionPostProcess, _super);
  49432. //ANY
  49433. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  49434. var _this = _super.call(this, name, "vrDistortionCorrection", [
  49435. 'LensCenter',
  49436. 'Scale',
  49437. 'ScaleIn',
  49438. 'HmdWarpParam'
  49439. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  49440. _this._isRightEye = isRightEye;
  49441. _this._distortionFactors = vrMetrics.distortionK;
  49442. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  49443. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  49444. _this.onSizeChangedObservable.add(function () {
  49445. _this.aspectRatio = _this.width * .5 / _this.height;
  49446. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  49447. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  49448. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  49449. });
  49450. _this.onApplyObservable.add(function (effect) {
  49451. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  49452. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  49453. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  49454. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  49455. });
  49456. return _this;
  49457. }
  49458. return VRDistortionCorrectionPostProcess;
  49459. }(BABYLON.PostProcess));
  49460. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  49461. })(BABYLON || (BABYLON = {}));
  49462. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  49463. // Mainly based on these 2 articles :
  49464. // 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
  49465. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  49466. var BABYLON;
  49467. (function (BABYLON) {
  49468. var JoystickAxis;
  49469. (function (JoystickAxis) {
  49470. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  49471. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  49472. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  49473. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  49474. var VirtualJoystick = (function () {
  49475. function VirtualJoystick(leftJoystick) {
  49476. var _this = this;
  49477. if (leftJoystick) {
  49478. this._leftJoystick = true;
  49479. }
  49480. else {
  49481. this._leftJoystick = false;
  49482. }
  49483. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  49484. VirtualJoystick._globalJoystickIndex++;
  49485. // By default left & right arrow keys are moving the X
  49486. // and up & down keys are moving the Y
  49487. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  49488. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  49489. this.reverseLeftRight = false;
  49490. this.reverseUpDown = false;
  49491. // collections of pointers
  49492. this._touches = new BABYLON.StringDictionary();
  49493. this.deltaPosition = BABYLON.Vector3.Zero();
  49494. this._joystickSensibility = 25;
  49495. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  49496. this._rotationSpeed = 25;
  49497. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  49498. this._rotateOnAxisRelativeToMesh = false;
  49499. this._onResize = function (evt) {
  49500. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  49501. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  49502. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  49503. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  49504. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  49505. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  49506. };
  49507. // injecting a canvas element on top of the canvas 3D game
  49508. if (!VirtualJoystick.vjCanvas) {
  49509. window.addEventListener("resize", this._onResize, false);
  49510. VirtualJoystick.vjCanvas = document.createElement("canvas");
  49511. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  49512. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  49513. VirtualJoystick.vjCanvas.width = window.innerWidth;
  49514. VirtualJoystick.vjCanvas.height = window.innerHeight;
  49515. VirtualJoystick.vjCanvas.style.width = "100%";
  49516. VirtualJoystick.vjCanvas.style.height = "100%";
  49517. VirtualJoystick.vjCanvas.style.position = "absolute";
  49518. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  49519. VirtualJoystick.vjCanvas.style.top = "0px";
  49520. VirtualJoystick.vjCanvas.style.left = "0px";
  49521. VirtualJoystick.vjCanvas.style.zIndex = "5";
  49522. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  49523. // Support for jQuery PEP polyfill
  49524. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  49525. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  49526. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  49527. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  49528. document.body.appendChild(VirtualJoystick.vjCanvas);
  49529. }
  49530. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  49531. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  49532. this.pressed = false;
  49533. // default joystick color
  49534. this._joystickColor = "cyan";
  49535. this._joystickPointerID = -1;
  49536. // current joystick position
  49537. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  49538. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  49539. // origin joystick position
  49540. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  49541. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  49542. this._onPointerDownHandlerRef = function (evt) {
  49543. _this._onPointerDown(evt);
  49544. };
  49545. this._onPointerMoveHandlerRef = function (evt) {
  49546. _this._onPointerMove(evt);
  49547. };
  49548. this._onPointerOutHandlerRef = function (evt) {
  49549. _this._onPointerUp(evt);
  49550. };
  49551. this._onPointerUpHandlerRef = function (evt) {
  49552. _this._onPointerUp(evt);
  49553. };
  49554. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  49555. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  49556. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  49557. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  49558. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  49559. evt.preventDefault(); // Disables system menu
  49560. }, false);
  49561. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  49562. }
  49563. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  49564. this._joystickSensibility = newJoystickSensibility;
  49565. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  49566. };
  49567. VirtualJoystick.prototype._onPointerDown = function (e) {
  49568. var positionOnScreenCondition;
  49569. e.preventDefault();
  49570. if (this._leftJoystick === true) {
  49571. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  49572. }
  49573. else {
  49574. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  49575. }
  49576. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  49577. // First contact will be dedicated to the virtual joystick
  49578. this._joystickPointerID = e.pointerId;
  49579. this._joystickPointerStartPos.x = e.clientX;
  49580. this._joystickPointerStartPos.y = e.clientY;
  49581. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  49582. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  49583. this._deltaJoystickVector.x = 0;
  49584. this._deltaJoystickVector.y = 0;
  49585. this.pressed = true;
  49586. this._touches.add(e.pointerId.toString(), e);
  49587. }
  49588. else {
  49589. // You can only trigger the action buttons with a joystick declared
  49590. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  49591. this._action();
  49592. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  49593. }
  49594. }
  49595. };
  49596. VirtualJoystick.prototype._onPointerMove = function (e) {
  49597. // If the current pointer is the one associated to the joystick (first touch contact)
  49598. if (this._joystickPointerID == e.pointerId) {
  49599. this._joystickPointerPos.x = e.clientX;
  49600. this._joystickPointerPos.y = e.clientY;
  49601. this._deltaJoystickVector = this._joystickPointerPos.clone();
  49602. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  49603. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  49604. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  49605. switch (this._axisTargetedByLeftAndRight) {
  49606. case JoystickAxis.X:
  49607. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  49608. break;
  49609. case JoystickAxis.Y:
  49610. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  49611. break;
  49612. case JoystickAxis.Z:
  49613. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  49614. break;
  49615. }
  49616. var directionUpDown = this.reverseUpDown ? 1 : -1;
  49617. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  49618. switch (this._axisTargetedByUpAndDown) {
  49619. case JoystickAxis.X:
  49620. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  49621. break;
  49622. case JoystickAxis.Y:
  49623. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  49624. break;
  49625. case JoystickAxis.Z:
  49626. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  49627. break;
  49628. }
  49629. }
  49630. else {
  49631. var data = this._touches.get(e.pointerId.toString());
  49632. if (data) {
  49633. data.x = e.clientX;
  49634. data.y = e.clientY;
  49635. }
  49636. }
  49637. };
  49638. VirtualJoystick.prototype._onPointerUp = function (e) {
  49639. if (this._joystickPointerID == e.pointerId) {
  49640. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  49641. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  49642. this._joystickPointerID = -1;
  49643. this.pressed = false;
  49644. }
  49645. else {
  49646. var touch = this._touches.get(e.pointerId.toString());
  49647. if (touch) {
  49648. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  49649. }
  49650. }
  49651. this._deltaJoystickVector.x = 0;
  49652. this._deltaJoystickVector.y = 0;
  49653. this._touches.remove(e.pointerId.toString());
  49654. };
  49655. /**
  49656. * Change the color of the virtual joystick
  49657. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  49658. */
  49659. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  49660. this._joystickColor = newColor;
  49661. };
  49662. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  49663. this._action = action;
  49664. };
  49665. // Define which axis you'd like to control for left & right
  49666. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  49667. switch (axis) {
  49668. case JoystickAxis.X:
  49669. case JoystickAxis.Y:
  49670. case JoystickAxis.Z:
  49671. this._axisTargetedByLeftAndRight = axis;
  49672. break;
  49673. default:
  49674. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  49675. break;
  49676. }
  49677. };
  49678. // Define which axis you'd like to control for up & down
  49679. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  49680. switch (axis) {
  49681. case JoystickAxis.X:
  49682. case JoystickAxis.Y:
  49683. case JoystickAxis.Z:
  49684. this._axisTargetedByUpAndDown = axis;
  49685. break;
  49686. default:
  49687. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  49688. break;
  49689. }
  49690. };
  49691. VirtualJoystick.prototype._clearCanvas = function () {
  49692. if (this._leftJoystick) {
  49693. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  49694. }
  49695. else {
  49696. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  49697. }
  49698. };
  49699. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  49700. var _this = this;
  49701. if (this.pressed) {
  49702. this._touches.forEach(function (key, touch) {
  49703. if (touch.pointerId === _this._joystickPointerID) {
  49704. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  49705. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  49706. VirtualJoystick.vjCanvasContext.beginPath();
  49707. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  49708. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  49709. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  49710. VirtualJoystick.vjCanvasContext.stroke();
  49711. VirtualJoystick.vjCanvasContext.closePath();
  49712. VirtualJoystick.vjCanvasContext.beginPath();
  49713. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  49714. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  49715. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  49716. VirtualJoystick.vjCanvasContext.stroke();
  49717. VirtualJoystick.vjCanvasContext.closePath();
  49718. VirtualJoystick.vjCanvasContext.beginPath();
  49719. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  49720. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  49721. VirtualJoystick.vjCanvasContext.stroke();
  49722. VirtualJoystick.vjCanvasContext.closePath();
  49723. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  49724. }
  49725. else {
  49726. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  49727. VirtualJoystick.vjCanvasContext.beginPath();
  49728. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  49729. VirtualJoystick.vjCanvasContext.beginPath();
  49730. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  49731. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  49732. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  49733. VirtualJoystick.vjCanvasContext.stroke();
  49734. VirtualJoystick.vjCanvasContext.closePath();
  49735. touch.prevX = touch.x;
  49736. touch.prevY = touch.y;
  49737. }
  49738. ;
  49739. });
  49740. }
  49741. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  49742. };
  49743. VirtualJoystick.prototype.releaseCanvas = function () {
  49744. if (VirtualJoystick.vjCanvas) {
  49745. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  49746. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  49747. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  49748. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  49749. window.removeEventListener("resize", this._onResize);
  49750. document.body.removeChild(VirtualJoystick.vjCanvas);
  49751. VirtualJoystick.vjCanvas = null;
  49752. }
  49753. };
  49754. return VirtualJoystick;
  49755. }());
  49756. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  49757. VirtualJoystick._globalJoystickIndex = 0;
  49758. BABYLON.VirtualJoystick = VirtualJoystick;
  49759. })(BABYLON || (BABYLON = {}));
  49760. //# sourceMappingURL=babylon.virtualJoystick.js.map
  49761. var BABYLON;
  49762. (function (BABYLON) {
  49763. // We're mainly based on the logic defined into the FreeCamera code
  49764. var VirtualJoysticksCamera = (function (_super) {
  49765. __extends(VirtualJoysticksCamera, _super);
  49766. function VirtualJoysticksCamera(name, position, scene) {
  49767. var _this = _super.call(this, name, position, scene) || this;
  49768. _this.inputs.addVirtualJoystick();
  49769. return _this;
  49770. }
  49771. VirtualJoysticksCamera.prototype.getClassName = function () {
  49772. return "VirtualJoysticksCamera";
  49773. };
  49774. return VirtualJoysticksCamera;
  49775. }(BABYLON.FreeCamera));
  49776. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  49777. })(BABYLON || (BABYLON = {}));
  49778. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  49779. var BABYLON;
  49780. (function (BABYLON) {
  49781. var FreeCameraVirtualJoystickInput = (function () {
  49782. function FreeCameraVirtualJoystickInput() {
  49783. }
  49784. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  49785. return this._leftjoystick;
  49786. };
  49787. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  49788. return this._rightjoystick;
  49789. };
  49790. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  49791. if (this._leftjoystick) {
  49792. var camera = this.camera;
  49793. var speed = camera._computeLocalCameraSpeed() * 50;
  49794. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  49795. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  49796. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  49797. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  49798. if (!this._leftjoystick.pressed) {
  49799. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  49800. }
  49801. if (!this._rightjoystick.pressed) {
  49802. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  49803. }
  49804. }
  49805. };
  49806. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  49807. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  49808. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  49809. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  49810. this._leftjoystick.setJoystickSensibility(0.15);
  49811. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  49812. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  49813. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  49814. this._rightjoystick.reverseUpDown = true;
  49815. this._rightjoystick.setJoystickSensibility(0.05);
  49816. this._rightjoystick.setJoystickColor("yellow");
  49817. };
  49818. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  49819. this._leftjoystick.releaseCanvas();
  49820. this._rightjoystick.releaseCanvas();
  49821. };
  49822. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  49823. return "FreeCameraVirtualJoystickInput";
  49824. };
  49825. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  49826. return "virtualJoystick";
  49827. };
  49828. return FreeCameraVirtualJoystickInput;
  49829. }());
  49830. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  49831. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  49832. })(BABYLON || (BABYLON = {}));
  49833. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  49834. var BABYLON;
  49835. (function (BABYLON) {
  49836. var AnaglyphPostProcess = (function (_super) {
  49837. __extends(AnaglyphPostProcess, _super);
  49838. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  49839. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  49840. _this._passedProcess = rigCameras[0]._rigPostProcess;
  49841. _this.onApplyObservable.add(function (effect) {
  49842. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  49843. });
  49844. return _this;
  49845. }
  49846. return AnaglyphPostProcess;
  49847. }(BABYLON.PostProcess));
  49848. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  49849. })(BABYLON || (BABYLON = {}));
  49850. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  49851. var BABYLON;
  49852. (function (BABYLON) {
  49853. var OutlineRenderer = (function () {
  49854. function OutlineRenderer(scene) {
  49855. this._scene = scene;
  49856. }
  49857. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  49858. var _this = this;
  49859. if (useOverlay === void 0) { useOverlay = false; }
  49860. var scene = this._scene;
  49861. var engine = this._scene.getEngine();
  49862. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  49863. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  49864. return;
  49865. }
  49866. var mesh = subMesh.getRenderingMesh();
  49867. var material = subMesh.getMaterial();
  49868. engine.enableEffect(this._effect);
  49869. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  49870. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  49871. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  49872. // Bones
  49873. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49874. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  49875. }
  49876. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  49877. // Alpha test
  49878. if (material && material.needAlphaTesting()) {
  49879. var alphaTexture = material.getAlphaTestTexture();
  49880. this._effect.setTexture("diffuseSampler", alphaTexture);
  49881. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  49882. }
  49883. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  49884. };
  49885. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  49886. var defines = [];
  49887. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  49888. var mesh = subMesh.getMesh();
  49889. var material = subMesh.getMaterial();
  49890. // Alpha test
  49891. if (material && material.needAlphaTesting()) {
  49892. defines.push("#define ALPHATEST");
  49893. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49894. attribs.push(BABYLON.VertexBuffer.UVKind);
  49895. defines.push("#define UV1");
  49896. }
  49897. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  49898. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  49899. defines.push("#define UV2");
  49900. }
  49901. }
  49902. // Bones
  49903. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49904. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  49905. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  49906. if (mesh.numBoneInfluencers > 4) {
  49907. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  49908. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  49909. }
  49910. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49911. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49912. }
  49913. else {
  49914. defines.push("#define NUM_BONE_INFLUENCERS 0");
  49915. }
  49916. // Instances
  49917. if (useInstances) {
  49918. defines.push("#define INSTANCES");
  49919. attribs.push("world0");
  49920. attribs.push("world1");
  49921. attribs.push("world2");
  49922. attribs.push("world3");
  49923. }
  49924. // Get correct effect
  49925. var join = defines.join("\n");
  49926. if (this._cachedDefines !== join) {
  49927. this._cachedDefines = join;
  49928. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  49929. }
  49930. return this._effect.isReady();
  49931. };
  49932. return OutlineRenderer;
  49933. }());
  49934. BABYLON.OutlineRenderer = OutlineRenderer;
  49935. })(BABYLON || (BABYLON = {}));
  49936. //# sourceMappingURL=babylon.outlineRenderer.js.map
  49937. var BABYLON;
  49938. (function (BABYLON) {
  49939. var MeshAssetTask = (function () {
  49940. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  49941. this.name = name;
  49942. this.meshesNames = meshesNames;
  49943. this.rootUrl = rootUrl;
  49944. this.sceneFilename = sceneFilename;
  49945. this.isCompleted = false;
  49946. }
  49947. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49948. var _this = this;
  49949. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  49950. _this.loadedMeshes = meshes;
  49951. _this.loadedParticleSystems = particleSystems;
  49952. _this.loadedSkeletons = skeletons;
  49953. _this.isCompleted = true;
  49954. if (_this.onSuccess) {
  49955. _this.onSuccess(_this);
  49956. }
  49957. onSuccess();
  49958. }, null, function () {
  49959. if (_this.onError) {
  49960. _this.onError(_this);
  49961. }
  49962. onError();
  49963. });
  49964. };
  49965. return MeshAssetTask;
  49966. }());
  49967. BABYLON.MeshAssetTask = MeshAssetTask;
  49968. var TextFileAssetTask = (function () {
  49969. function TextFileAssetTask(name, url) {
  49970. this.name = name;
  49971. this.url = url;
  49972. this.isCompleted = false;
  49973. }
  49974. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49975. var _this = this;
  49976. BABYLON.Tools.LoadFile(this.url, function (data) {
  49977. _this.text = data;
  49978. _this.isCompleted = true;
  49979. if (_this.onSuccess) {
  49980. _this.onSuccess(_this);
  49981. }
  49982. onSuccess();
  49983. }, null, scene.database, false, function () {
  49984. if (_this.onError) {
  49985. _this.onError(_this);
  49986. }
  49987. onError();
  49988. });
  49989. };
  49990. return TextFileAssetTask;
  49991. }());
  49992. BABYLON.TextFileAssetTask = TextFileAssetTask;
  49993. var BinaryFileAssetTask = (function () {
  49994. function BinaryFileAssetTask(name, url) {
  49995. this.name = name;
  49996. this.url = url;
  49997. this.isCompleted = false;
  49998. }
  49999. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50000. var _this = this;
  50001. BABYLON.Tools.LoadFile(this.url, function (data) {
  50002. _this.data = data;
  50003. _this.isCompleted = true;
  50004. if (_this.onSuccess) {
  50005. _this.onSuccess(_this);
  50006. }
  50007. onSuccess();
  50008. }, null, scene.database, true, function () {
  50009. if (_this.onError) {
  50010. _this.onError(_this);
  50011. }
  50012. onError();
  50013. });
  50014. };
  50015. return BinaryFileAssetTask;
  50016. }());
  50017. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  50018. var ImageAssetTask = (function () {
  50019. function ImageAssetTask(name, url) {
  50020. this.name = name;
  50021. this.url = url;
  50022. this.isCompleted = false;
  50023. }
  50024. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50025. var _this = this;
  50026. var img = new Image();
  50027. BABYLON.Tools.SetCorsBehavior(this.url, img);
  50028. img.onload = function () {
  50029. _this.image = img;
  50030. _this.isCompleted = true;
  50031. if (_this.onSuccess) {
  50032. _this.onSuccess(_this);
  50033. }
  50034. onSuccess();
  50035. };
  50036. img.onerror = function () {
  50037. if (_this.onError) {
  50038. _this.onError(_this);
  50039. }
  50040. onError();
  50041. };
  50042. img.src = this.url;
  50043. };
  50044. return ImageAssetTask;
  50045. }());
  50046. BABYLON.ImageAssetTask = ImageAssetTask;
  50047. var TextureAssetTask = (function () {
  50048. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  50049. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50050. this.name = name;
  50051. this.url = url;
  50052. this.noMipmap = noMipmap;
  50053. this.invertY = invertY;
  50054. this.samplingMode = samplingMode;
  50055. this.isCompleted = false;
  50056. }
  50057. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50058. var _this = this;
  50059. var onload = function () {
  50060. _this.isCompleted = true;
  50061. if (_this.onSuccess) {
  50062. _this.onSuccess(_this);
  50063. }
  50064. onSuccess();
  50065. };
  50066. var onerror = function () {
  50067. if (_this.onError) {
  50068. _this.onError(_this);
  50069. }
  50070. onError();
  50071. };
  50072. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  50073. };
  50074. return TextureAssetTask;
  50075. }());
  50076. BABYLON.TextureAssetTask = TextureAssetTask;
  50077. var CubeTextureAssetTask = (function () {
  50078. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  50079. this.name = name;
  50080. this.url = url;
  50081. this.extensions = extensions;
  50082. this.noMipmap = noMipmap;
  50083. this.files = files;
  50084. this.isCompleted = false;
  50085. }
  50086. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50087. var _this = this;
  50088. var onload = function () {
  50089. _this.isCompleted = true;
  50090. if (_this.onSuccess) {
  50091. _this.onSuccess(_this);
  50092. }
  50093. onSuccess();
  50094. };
  50095. var onerror = function () {
  50096. if (_this.onError) {
  50097. _this.onError(_this);
  50098. }
  50099. onError();
  50100. };
  50101. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  50102. };
  50103. return CubeTextureAssetTask;
  50104. }());
  50105. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  50106. var HDRCubeTextureAssetTask = (function () {
  50107. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  50108. if (noMipmap === void 0) { noMipmap = false; }
  50109. if (generateHarmonics === void 0) { generateHarmonics = true; }
  50110. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  50111. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  50112. this.name = name;
  50113. this.url = url;
  50114. this.size = size;
  50115. this.noMipmap = noMipmap;
  50116. this.generateHarmonics = generateHarmonics;
  50117. this.useInGammaSpace = useInGammaSpace;
  50118. this.usePMREMGenerator = usePMREMGenerator;
  50119. this.isCompleted = false;
  50120. }
  50121. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50122. var _this = this;
  50123. var onload = function () {
  50124. _this.isCompleted = true;
  50125. if (_this.onSuccess) {
  50126. _this.onSuccess(_this);
  50127. }
  50128. onSuccess();
  50129. };
  50130. var onerror = function () {
  50131. if (_this.onError) {
  50132. _this.onError(_this);
  50133. }
  50134. onError();
  50135. };
  50136. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  50137. };
  50138. return HDRCubeTextureAssetTask;
  50139. }());
  50140. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  50141. var AssetsManager = (function () {
  50142. function AssetsManager(scene) {
  50143. this.tasks = new Array();
  50144. this.waitingTasksCount = 0;
  50145. this.useDefaultLoadingScreen = true;
  50146. this._scene = scene;
  50147. }
  50148. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  50149. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  50150. this.tasks.push(task);
  50151. return task;
  50152. };
  50153. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  50154. var task = new TextFileAssetTask(taskName, url);
  50155. this.tasks.push(task);
  50156. return task;
  50157. };
  50158. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  50159. var task = new BinaryFileAssetTask(taskName, url);
  50160. this.tasks.push(task);
  50161. return task;
  50162. };
  50163. AssetsManager.prototype.addImageTask = function (taskName, url) {
  50164. var task = new ImageAssetTask(taskName, url);
  50165. this.tasks.push(task);
  50166. return task;
  50167. };
  50168. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  50169. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50170. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  50171. this.tasks.push(task);
  50172. return task;
  50173. };
  50174. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  50175. this.waitingTasksCount--;
  50176. if (this.waitingTasksCount === 0) {
  50177. if (this.onFinish) {
  50178. this.onFinish(this.tasks);
  50179. }
  50180. this._scene.getEngine().hideLoadingUI();
  50181. }
  50182. };
  50183. AssetsManager.prototype._runTask = function (task) {
  50184. var _this = this;
  50185. task.run(this._scene, function () {
  50186. if (_this.onTaskSuccess) {
  50187. _this.onTaskSuccess(task);
  50188. }
  50189. _this._decreaseWaitingTasksCount();
  50190. }, function () {
  50191. if (_this.onTaskError) {
  50192. _this.onTaskError(task);
  50193. }
  50194. _this._decreaseWaitingTasksCount();
  50195. });
  50196. };
  50197. AssetsManager.prototype.reset = function () {
  50198. this.tasks = new Array();
  50199. return this;
  50200. };
  50201. AssetsManager.prototype.load = function () {
  50202. this.waitingTasksCount = this.tasks.length;
  50203. if (this.waitingTasksCount === 0) {
  50204. if (this.onFinish) {
  50205. this.onFinish(this.tasks);
  50206. }
  50207. return this;
  50208. }
  50209. if (this.useDefaultLoadingScreen) {
  50210. this._scene.getEngine().displayLoadingUI();
  50211. }
  50212. for (var index = 0; index < this.tasks.length; index++) {
  50213. var task = this.tasks[index];
  50214. this._runTask(task);
  50215. }
  50216. return this;
  50217. };
  50218. return AssetsManager;
  50219. }());
  50220. BABYLON.AssetsManager = AssetsManager;
  50221. })(BABYLON || (BABYLON = {}));
  50222. //# sourceMappingURL=babylon.assetsManager.js.map
  50223. var BABYLON;
  50224. (function (BABYLON) {
  50225. var VRCameraMetrics = (function () {
  50226. function VRCameraMetrics() {
  50227. this.compensateDistortion = true;
  50228. }
  50229. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  50230. get: function () {
  50231. return this.hResolution / (2 * this.vResolution);
  50232. },
  50233. enumerable: true,
  50234. configurable: true
  50235. });
  50236. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  50237. get: function () {
  50238. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  50239. },
  50240. enumerable: true,
  50241. configurable: true
  50242. });
  50243. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  50244. get: function () {
  50245. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  50246. var h = (4 * meters) / this.hScreenSize;
  50247. return BABYLON.Matrix.Translation(h, 0, 0);
  50248. },
  50249. enumerable: true,
  50250. configurable: true
  50251. });
  50252. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  50253. get: function () {
  50254. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  50255. var h = (4 * meters) / this.hScreenSize;
  50256. return BABYLON.Matrix.Translation(-h, 0, 0);
  50257. },
  50258. enumerable: true,
  50259. configurable: true
  50260. });
  50261. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  50262. get: function () {
  50263. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  50264. },
  50265. enumerable: true,
  50266. configurable: true
  50267. });
  50268. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  50269. get: function () {
  50270. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  50271. },
  50272. enumerable: true,
  50273. configurable: true
  50274. });
  50275. VRCameraMetrics.GetDefault = function () {
  50276. var result = new VRCameraMetrics();
  50277. result.hResolution = 1280;
  50278. result.vResolution = 800;
  50279. result.hScreenSize = 0.149759993;
  50280. result.vScreenSize = 0.0935999975;
  50281. result.vScreenCenter = 0.0467999987;
  50282. result.eyeToScreenDistance = 0.0410000011;
  50283. result.lensSeparationDistance = 0.0635000020;
  50284. result.interpupillaryDistance = 0.0640000030;
  50285. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  50286. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  50287. result.postProcessScaleFactor = 1.714605507808412;
  50288. result.lensCenterOffset = 0.151976421;
  50289. return result;
  50290. };
  50291. return VRCameraMetrics;
  50292. }());
  50293. BABYLON.VRCameraMetrics = VRCameraMetrics;
  50294. })(BABYLON || (BABYLON = {}));
  50295. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  50296. var BABYLON;
  50297. (function (BABYLON) {
  50298. var WebVRFreeCamera = (function (_super) {
  50299. __extends(WebVRFreeCamera, _super);
  50300. function WebVRFreeCamera(name, position, scene, webVROptions) {
  50301. if (webVROptions === void 0) { webVROptions = {}; }
  50302. var _this = _super.call(this, name, position, scene) || this;
  50303. _this.webVROptions = webVROptions;
  50304. _this._vrDevice = null;
  50305. _this.rawPose = null;
  50306. _this._vrEnabled = false;
  50307. _this._attached = false;
  50308. _this._positionOffset = BABYLON.Vector3.Zero();
  50309. _this._descendants = [];
  50310. _this.devicePosition = BABYLON.Vector3.Zero();
  50311. _this.deviceScaleFactor = 1;
  50312. _this.controllers = [];
  50313. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  50314. //legacy support - the compensation boolean was removed.
  50315. if (arguments.length === 5) {
  50316. _this.webVROptions = arguments[4];
  50317. }
  50318. // default webVR options
  50319. if (_this.webVROptions.trackPosition == undefined) {
  50320. _this.webVROptions.trackPosition = true;
  50321. }
  50322. if (_this.webVROptions.controllerMeshes == undefined) {
  50323. _this.webVROptions.controllerMeshes = true;
  50324. }
  50325. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  50326. _this.webVROptions.defaultLightningOnControllers = true;
  50327. }
  50328. _this.rotationQuaternion = new BABYLON.Quaternion();
  50329. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  50330. if (_this.webVROptions && _this.webVROptions.positionScale) {
  50331. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  50332. }
  50333. //enable VR
  50334. _this.getEngine().initWebVR();
  50335. if (!_this.getEngine().vrDisplaysPromise) {
  50336. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  50337. }
  50338. else {
  50339. _this._frameData = new VRFrameData();
  50340. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  50341. if (devices.length > 0) {
  50342. _this._vrEnabled = true;
  50343. if (_this.webVROptions.displayName) {
  50344. var found = devices.some(function (device) {
  50345. if (device.displayName === _this.webVROptions.displayName) {
  50346. _this._vrDevice = device;
  50347. return true;
  50348. }
  50349. else {
  50350. return false;
  50351. }
  50352. });
  50353. if (!found) {
  50354. _this._vrDevice = devices[0];
  50355. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  50356. }
  50357. }
  50358. else {
  50359. //choose the first one
  50360. _this._vrDevice = devices[0];
  50361. }
  50362. //reset the rig parameters.
  50363. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData });
  50364. if (_this._attached) {
  50365. _this.getEngine().enableVR(_this._vrDevice);
  50366. }
  50367. }
  50368. else {
  50369. BABYLON.Tools.Error("No WebVR devices found!");
  50370. }
  50371. });
  50372. }
  50373. // try to attach the controllers, if found.
  50374. _this.initControllers();
  50375. /**
  50376. * The idea behind the following lines:
  50377. * objects that have the camera as parent should actually have the rig cameras as a parent.
  50378. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  50379. * the second will not show it correctly.
  50380. *
  50381. * To solve this - each object that has the camera as parent will be added to a protected array.
  50382. * When the rig camera renders, it will take this array and set all of those to be its children.
  50383. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  50384. * Amazing!
  50385. */
  50386. scene.onBeforeCameraRenderObservable.add(function (camera) {
  50387. if (camera.parent === _this && _this.rigParenting) {
  50388. _this._descendants = _this.getDescendants(true, function (n) {
  50389. // don't take the cameras or the controllers!
  50390. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  50391. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  50392. return !isController && !isRigCamera;
  50393. });
  50394. _this._descendants.forEach(function (node) {
  50395. node.parent = camera;
  50396. });
  50397. }
  50398. });
  50399. scene.onAfterCameraRenderObservable.add(function (camera) {
  50400. if (camera.parent === _this && _this.rigParenting) {
  50401. _this._descendants.forEach(function (node) {
  50402. node.parent = _this;
  50403. });
  50404. }
  50405. });
  50406. return _this;
  50407. }
  50408. WebVRFreeCamera.prototype._checkInputs = function () {
  50409. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  50410. var currentPose = this._frameData.pose;
  50411. this.updateFromDevice(currentPose);
  50412. }
  50413. _super.prototype._checkInputs.call(this);
  50414. };
  50415. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  50416. if (poseData && poseData.orientation) {
  50417. this.rawPose = poseData;
  50418. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  50419. if (this.getScene().useRightHandedSystem) {
  50420. this.deviceRotationQuaternion.z *= -1;
  50421. this.deviceRotationQuaternion.w *= -1;
  50422. }
  50423. if (this.webVROptions.trackPosition && this.rawPose.position) {
  50424. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  50425. if (this.getScene().useRightHandedSystem) {
  50426. this.devicePosition.z *= -1;
  50427. }
  50428. }
  50429. }
  50430. };
  50431. /**
  50432. * WebVR's attach control will start broadcasting frames to the device.
  50433. * Note that in certain browsers (chrome for example) this function must be called
  50434. * within a user-interaction callback. Example:
  50435. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  50436. *
  50437. * @param {HTMLElement} element
  50438. * @param {boolean} [noPreventDefault]
  50439. *
  50440. * @memberOf WebVRFreeCamera
  50441. */
  50442. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  50443. _super.prototype.attachControl.call(this, element, noPreventDefault);
  50444. this._attached = true;
  50445. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  50446. if (this._vrEnabled) {
  50447. this.getEngine().enableVR(this._vrDevice);
  50448. }
  50449. };
  50450. WebVRFreeCamera.prototype.detachControl = function (element) {
  50451. _super.prototype.detachControl.call(this, element);
  50452. this._vrEnabled = false;
  50453. this._attached = false;
  50454. this.getEngine().disableVR();
  50455. };
  50456. WebVRFreeCamera.prototype.getClassName = function () {
  50457. return "WebVRFreeCamera";
  50458. };
  50459. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  50460. //uses the vrDisplay's "resetPose()".
  50461. //pitch and roll won't be affected.
  50462. this._vrDevice.resetPose();
  50463. };
  50464. WebVRFreeCamera.prototype._updateRigCameras = function () {
  50465. var camLeft = this._rigCameras[0];
  50466. var camRight = this._rigCameras[1];
  50467. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  50468. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  50469. camLeft.position.copyFrom(this.devicePosition);
  50470. camRight.position.copyFrom(this.devicePosition);
  50471. };
  50472. /**
  50473. * This function is called by the two RIG cameras.
  50474. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  50475. */
  50476. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  50477. var _this = this;
  50478. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  50479. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  50480. if (!this.getScene().useRightHandedSystem) {
  50481. [2, 6, 8, 9, 14].forEach(function (num) {
  50482. _this._webvrViewMatrix.m[num] *= -1;
  50483. });
  50484. }
  50485. var parentCamera = this._cameraRigParams["parentCamera"];
  50486. // should the view matrix be updated with scale and position offset?
  50487. if (parentCamera.deviceScaleFactor !== 1) {
  50488. this._webvrViewMatrix.invert();
  50489. // scale the position, if set
  50490. if (parentCamera.deviceScaleFactor) {
  50491. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  50492. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  50493. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  50494. }
  50495. this._webvrViewMatrix.invert();
  50496. }
  50497. // update the camera rotation matrix
  50498. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  50499. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  50500. // Computing target and final matrix
  50501. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  50502. return this._webvrViewMatrix;
  50503. };
  50504. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  50505. var _this = this;
  50506. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  50507. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  50508. //babylon compatible matrix
  50509. if (!this.getScene().useRightHandedSystem) {
  50510. [8, 9, 10, 11].forEach(function (num) {
  50511. _this._projectionMatrix.m[num] *= -1;
  50512. });
  50513. }
  50514. return this._projectionMatrix;
  50515. };
  50516. WebVRFreeCamera.prototype.initControllers = function () {
  50517. var _this = this;
  50518. this.controllers = [];
  50519. new BABYLON.Gamepads(function (gp) {
  50520. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  50521. var webVrController = gp;
  50522. if (_this.webVROptions.controllerMeshes) {
  50523. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  50524. if (_this.webVROptions.defaultLightningOnControllers) {
  50525. if (!_this._lightOnControllers) {
  50526. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  50527. }
  50528. loadedMesh.getChildren().forEach(function (mesh) {
  50529. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  50530. });
  50531. }
  50532. });
  50533. }
  50534. webVrController.attachToPoseControlledCamera(_this);
  50535. // since this is async - sanity check. Is the controller already stored?
  50536. if (_this.controllers.indexOf(webVrController) === -1) {
  50537. //add to the controllers array
  50538. _this.controllers.push(webVrController);
  50539. //did we find enough controllers? Great! let the developer know.
  50540. if (_this.onControllersAttached && _this.controllers.length === 2) {
  50541. _this.onControllersAttached(_this.controllers);
  50542. }
  50543. }
  50544. }
  50545. });
  50546. };
  50547. return WebVRFreeCamera;
  50548. }(BABYLON.FreeCamera));
  50549. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  50550. })(BABYLON || (BABYLON = {}));
  50551. //# sourceMappingURL=babylon.webVRCamera.js.map
  50552. var BABYLON;
  50553. (function (BABYLON) {
  50554. // Standard optimizations
  50555. var SceneOptimization = (function () {
  50556. function SceneOptimization(priority) {
  50557. if (priority === void 0) { priority = 0; }
  50558. this.priority = priority;
  50559. this.apply = function (scene) {
  50560. return true; // Return true if everything that can be done was applied
  50561. };
  50562. }
  50563. return SceneOptimization;
  50564. }());
  50565. BABYLON.SceneOptimization = SceneOptimization;
  50566. var TextureOptimization = (function (_super) {
  50567. __extends(TextureOptimization, _super);
  50568. function TextureOptimization(priority, maximumSize) {
  50569. if (priority === void 0) { priority = 0; }
  50570. if (maximumSize === void 0) { maximumSize = 1024; }
  50571. var _this = _super.call(this, priority) || this;
  50572. _this.priority = priority;
  50573. _this.maximumSize = maximumSize;
  50574. _this.apply = function (scene) {
  50575. var allDone = true;
  50576. for (var index = 0; index < scene.textures.length; index++) {
  50577. var texture = scene.textures[index];
  50578. if (!texture.canRescale) {
  50579. continue;
  50580. }
  50581. var currentSize = texture.getSize();
  50582. var maxDimension = Math.max(currentSize.width, currentSize.height);
  50583. if (maxDimension > _this.maximumSize) {
  50584. texture.scale(0.5);
  50585. allDone = false;
  50586. }
  50587. }
  50588. return allDone;
  50589. };
  50590. return _this;
  50591. }
  50592. return TextureOptimization;
  50593. }(SceneOptimization));
  50594. BABYLON.TextureOptimization = TextureOptimization;
  50595. var HardwareScalingOptimization = (function (_super) {
  50596. __extends(HardwareScalingOptimization, _super);
  50597. function HardwareScalingOptimization(priority, maximumScale) {
  50598. if (priority === void 0) { priority = 0; }
  50599. if (maximumScale === void 0) { maximumScale = 2; }
  50600. var _this = _super.call(this, priority) || this;
  50601. _this.priority = priority;
  50602. _this.maximumScale = maximumScale;
  50603. _this._currentScale = 1;
  50604. _this.apply = function (scene) {
  50605. _this._currentScale++;
  50606. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  50607. return _this._currentScale >= _this.maximumScale;
  50608. };
  50609. return _this;
  50610. }
  50611. return HardwareScalingOptimization;
  50612. }(SceneOptimization));
  50613. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  50614. var ShadowsOptimization = (function (_super) {
  50615. __extends(ShadowsOptimization, _super);
  50616. function ShadowsOptimization() {
  50617. var _this = _super !== null && _super.apply(this, arguments) || this;
  50618. _this.apply = function (scene) {
  50619. scene.shadowsEnabled = false;
  50620. return true;
  50621. };
  50622. return _this;
  50623. }
  50624. return ShadowsOptimization;
  50625. }(SceneOptimization));
  50626. BABYLON.ShadowsOptimization = ShadowsOptimization;
  50627. var PostProcessesOptimization = (function (_super) {
  50628. __extends(PostProcessesOptimization, _super);
  50629. function PostProcessesOptimization() {
  50630. var _this = _super !== null && _super.apply(this, arguments) || this;
  50631. _this.apply = function (scene) {
  50632. scene.postProcessesEnabled = false;
  50633. return true;
  50634. };
  50635. return _this;
  50636. }
  50637. return PostProcessesOptimization;
  50638. }(SceneOptimization));
  50639. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  50640. var LensFlaresOptimization = (function (_super) {
  50641. __extends(LensFlaresOptimization, _super);
  50642. function LensFlaresOptimization() {
  50643. var _this = _super !== null && _super.apply(this, arguments) || this;
  50644. _this.apply = function (scene) {
  50645. scene.lensFlaresEnabled = false;
  50646. return true;
  50647. };
  50648. return _this;
  50649. }
  50650. return LensFlaresOptimization;
  50651. }(SceneOptimization));
  50652. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  50653. var ParticlesOptimization = (function (_super) {
  50654. __extends(ParticlesOptimization, _super);
  50655. function ParticlesOptimization() {
  50656. var _this = _super !== null && _super.apply(this, arguments) || this;
  50657. _this.apply = function (scene) {
  50658. scene.particlesEnabled = false;
  50659. return true;
  50660. };
  50661. return _this;
  50662. }
  50663. return ParticlesOptimization;
  50664. }(SceneOptimization));
  50665. BABYLON.ParticlesOptimization = ParticlesOptimization;
  50666. var RenderTargetsOptimization = (function (_super) {
  50667. __extends(RenderTargetsOptimization, _super);
  50668. function RenderTargetsOptimization() {
  50669. var _this = _super !== null && _super.apply(this, arguments) || this;
  50670. _this.apply = function (scene) {
  50671. scene.renderTargetsEnabled = false;
  50672. return true;
  50673. };
  50674. return _this;
  50675. }
  50676. return RenderTargetsOptimization;
  50677. }(SceneOptimization));
  50678. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  50679. var MergeMeshesOptimization = (function (_super) {
  50680. __extends(MergeMeshesOptimization, _super);
  50681. function MergeMeshesOptimization() {
  50682. var _this = _super !== null && _super.apply(this, arguments) || this;
  50683. _this._canBeMerged = function (abstractMesh) {
  50684. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  50685. return false;
  50686. }
  50687. var mesh = abstractMesh;
  50688. if (!mesh.isVisible || !mesh.isEnabled()) {
  50689. return false;
  50690. }
  50691. if (mesh.instances.length > 0) {
  50692. return false;
  50693. }
  50694. if (mesh.skeleton || mesh.hasLODLevels) {
  50695. return false;
  50696. }
  50697. if (mesh.parent) {
  50698. return false;
  50699. }
  50700. return true;
  50701. };
  50702. _this.apply = function (scene, updateSelectionTree) {
  50703. var globalPool = scene.meshes.slice(0);
  50704. var globalLength = globalPool.length;
  50705. for (var index = 0; index < globalLength; index++) {
  50706. var currentPool = new Array();
  50707. var current = globalPool[index];
  50708. // Checks
  50709. if (!_this._canBeMerged(current)) {
  50710. continue;
  50711. }
  50712. currentPool.push(current);
  50713. // Find compatible meshes
  50714. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  50715. var otherMesh = globalPool[subIndex];
  50716. if (!_this._canBeMerged(otherMesh)) {
  50717. continue;
  50718. }
  50719. if (otherMesh.material !== current.material) {
  50720. continue;
  50721. }
  50722. if (otherMesh.checkCollisions !== current.checkCollisions) {
  50723. continue;
  50724. }
  50725. currentPool.push(otherMesh);
  50726. globalLength--;
  50727. globalPool.splice(subIndex, 1);
  50728. subIndex--;
  50729. }
  50730. if (currentPool.length < 2) {
  50731. continue;
  50732. }
  50733. // Merge meshes
  50734. BABYLON.Mesh.MergeMeshes(currentPool);
  50735. }
  50736. if (updateSelectionTree != undefined) {
  50737. if (updateSelectionTree) {
  50738. scene.createOrUpdateSelectionOctree();
  50739. }
  50740. }
  50741. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  50742. scene.createOrUpdateSelectionOctree();
  50743. }
  50744. return true;
  50745. };
  50746. return _this;
  50747. }
  50748. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  50749. get: function () {
  50750. return MergeMeshesOptimization._UpdateSelectionTree;
  50751. },
  50752. set: function (value) {
  50753. MergeMeshesOptimization._UpdateSelectionTree = value;
  50754. },
  50755. enumerable: true,
  50756. configurable: true
  50757. });
  50758. return MergeMeshesOptimization;
  50759. }(SceneOptimization));
  50760. MergeMeshesOptimization._UpdateSelectionTree = false;
  50761. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  50762. // Options
  50763. var SceneOptimizerOptions = (function () {
  50764. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  50765. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  50766. if (trackerDuration === void 0) { trackerDuration = 2000; }
  50767. this.targetFrameRate = targetFrameRate;
  50768. this.trackerDuration = trackerDuration;
  50769. this.optimizations = new Array();
  50770. }
  50771. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  50772. var result = new SceneOptimizerOptions(targetFrameRate);
  50773. var priority = 0;
  50774. result.optimizations.push(new MergeMeshesOptimization(priority));
  50775. result.optimizations.push(new ShadowsOptimization(priority));
  50776. result.optimizations.push(new LensFlaresOptimization(priority));
  50777. // Next priority
  50778. priority++;
  50779. result.optimizations.push(new PostProcessesOptimization(priority));
  50780. result.optimizations.push(new ParticlesOptimization(priority));
  50781. // Next priority
  50782. priority++;
  50783. result.optimizations.push(new TextureOptimization(priority, 1024));
  50784. return result;
  50785. };
  50786. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  50787. var result = new SceneOptimizerOptions(targetFrameRate);
  50788. var priority = 0;
  50789. result.optimizations.push(new MergeMeshesOptimization(priority));
  50790. result.optimizations.push(new ShadowsOptimization(priority));
  50791. result.optimizations.push(new LensFlaresOptimization(priority));
  50792. // Next priority
  50793. priority++;
  50794. result.optimizations.push(new PostProcessesOptimization(priority));
  50795. result.optimizations.push(new ParticlesOptimization(priority));
  50796. // Next priority
  50797. priority++;
  50798. result.optimizations.push(new TextureOptimization(priority, 512));
  50799. // Next priority
  50800. priority++;
  50801. result.optimizations.push(new RenderTargetsOptimization(priority));
  50802. // Next priority
  50803. priority++;
  50804. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  50805. return result;
  50806. };
  50807. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  50808. var result = new SceneOptimizerOptions(targetFrameRate);
  50809. var priority = 0;
  50810. result.optimizations.push(new MergeMeshesOptimization(priority));
  50811. result.optimizations.push(new ShadowsOptimization(priority));
  50812. result.optimizations.push(new LensFlaresOptimization(priority));
  50813. // Next priority
  50814. priority++;
  50815. result.optimizations.push(new PostProcessesOptimization(priority));
  50816. result.optimizations.push(new ParticlesOptimization(priority));
  50817. // Next priority
  50818. priority++;
  50819. result.optimizations.push(new TextureOptimization(priority, 256));
  50820. // Next priority
  50821. priority++;
  50822. result.optimizations.push(new RenderTargetsOptimization(priority));
  50823. // Next priority
  50824. priority++;
  50825. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  50826. return result;
  50827. };
  50828. return SceneOptimizerOptions;
  50829. }());
  50830. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  50831. // Scene optimizer tool
  50832. var SceneOptimizer = (function () {
  50833. function SceneOptimizer() {
  50834. }
  50835. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  50836. // TODO: add an epsilon
  50837. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  50838. if (onSuccess) {
  50839. onSuccess();
  50840. }
  50841. return;
  50842. }
  50843. // Apply current level of optimizations
  50844. var allDone = true;
  50845. var noOptimizationApplied = true;
  50846. for (var index = 0; index < options.optimizations.length; index++) {
  50847. var optimization = options.optimizations[index];
  50848. if (optimization.priority === currentPriorityLevel) {
  50849. noOptimizationApplied = false;
  50850. allDone = allDone && optimization.apply(scene);
  50851. }
  50852. }
  50853. // If no optimization was applied, this is a failure :(
  50854. if (noOptimizationApplied) {
  50855. if (onFailure) {
  50856. onFailure();
  50857. }
  50858. return;
  50859. }
  50860. // If all optimizations were done, move to next level
  50861. if (allDone) {
  50862. currentPriorityLevel++;
  50863. }
  50864. // Let's the system running for a specific amount of time before checking FPS
  50865. scene.executeWhenReady(function () {
  50866. setTimeout(function () {
  50867. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  50868. }, options.trackerDuration);
  50869. });
  50870. };
  50871. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  50872. if (!options) {
  50873. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  50874. }
  50875. // Let's the system running for a specific amount of time before checking FPS
  50876. scene.executeWhenReady(function () {
  50877. setTimeout(function () {
  50878. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  50879. }, options.trackerDuration);
  50880. });
  50881. };
  50882. return SceneOptimizer;
  50883. }());
  50884. BABYLON.SceneOptimizer = SceneOptimizer;
  50885. })(BABYLON || (BABYLON = {}));
  50886. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  50887. var BABYLON;
  50888. (function (BABYLON) {
  50889. var Internals;
  50890. (function (Internals) {
  50891. var MeshLODLevel = (function () {
  50892. function MeshLODLevel(distance, mesh) {
  50893. this.distance = distance;
  50894. this.mesh = mesh;
  50895. }
  50896. return MeshLODLevel;
  50897. }());
  50898. Internals.MeshLODLevel = MeshLODLevel;
  50899. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50900. })(BABYLON || (BABYLON = {}));
  50901. //# sourceMappingURL=babylon.meshLODLevel.js.map
  50902. var BABYLON;
  50903. (function (BABYLON) {
  50904. var RawTexture = (function (_super) {
  50905. __extends(RawTexture, _super);
  50906. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  50907. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50908. if (invertY === void 0) { invertY = false; }
  50909. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50910. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50911. _this.format = format;
  50912. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  50913. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50914. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50915. return _this;
  50916. }
  50917. RawTexture.prototype.update = function (data) {
  50918. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  50919. };
  50920. // Statics
  50921. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50922. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50923. if (invertY === void 0) { invertY = false; }
  50924. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50925. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  50926. };
  50927. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50928. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50929. if (invertY === void 0) { invertY = false; }
  50930. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50931. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50932. };
  50933. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50934. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50935. if (invertY === void 0) { invertY = false; }
  50936. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50937. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50938. };
  50939. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50940. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50941. if (invertY === void 0) { invertY = false; }
  50942. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50943. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  50944. };
  50945. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50946. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50947. if (invertY === void 0) { invertY = false; }
  50948. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50949. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  50950. };
  50951. return RawTexture;
  50952. }(BABYLON.Texture));
  50953. BABYLON.RawTexture = RawTexture;
  50954. })(BABYLON || (BABYLON = {}));
  50955. //# sourceMappingURL=babylon.rawTexture.js.map
  50956. /// <reference path="..\Math\babylon.math.ts" />
  50957. var BABYLON;
  50958. (function (BABYLON) {
  50959. var IndexedVector2 = (function (_super) {
  50960. __extends(IndexedVector2, _super);
  50961. function IndexedVector2(original, index) {
  50962. var _this = _super.call(this, original.x, original.y) || this;
  50963. _this.index = index;
  50964. return _this;
  50965. }
  50966. return IndexedVector2;
  50967. }(BABYLON.Vector2));
  50968. var PolygonPoints = (function () {
  50969. function PolygonPoints() {
  50970. this.elements = new Array();
  50971. }
  50972. PolygonPoints.prototype.add = function (originalPoints) {
  50973. var _this = this;
  50974. var result = new Array();
  50975. originalPoints.forEach(function (point) {
  50976. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  50977. var newPoint = new IndexedVector2(point, _this.elements.length);
  50978. result.push(newPoint);
  50979. _this.elements.push(newPoint);
  50980. }
  50981. });
  50982. return result;
  50983. };
  50984. PolygonPoints.prototype.computeBounds = function () {
  50985. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  50986. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  50987. this.elements.forEach(function (point) {
  50988. // x
  50989. if (point.x < lmin.x) {
  50990. lmin.x = point.x;
  50991. }
  50992. else if (point.x > lmax.x) {
  50993. lmax.x = point.x;
  50994. }
  50995. // y
  50996. if (point.y < lmin.y) {
  50997. lmin.y = point.y;
  50998. }
  50999. else if (point.y > lmax.y) {
  51000. lmax.y = point.y;
  51001. }
  51002. });
  51003. return {
  51004. min: lmin,
  51005. max: lmax,
  51006. width: lmax.x - lmin.x,
  51007. height: lmax.y - lmin.y
  51008. };
  51009. };
  51010. return PolygonPoints;
  51011. }());
  51012. var Polygon = (function () {
  51013. function Polygon() {
  51014. }
  51015. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  51016. return [
  51017. new BABYLON.Vector2(xmin, ymin),
  51018. new BABYLON.Vector2(xmax, ymin),
  51019. new BABYLON.Vector2(xmax, ymax),
  51020. new BABYLON.Vector2(xmin, ymax)
  51021. ];
  51022. };
  51023. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  51024. if (cx === void 0) { cx = 0; }
  51025. if (cy === void 0) { cy = 0; }
  51026. if (numberOfSides === void 0) { numberOfSides = 32; }
  51027. var result = new Array();
  51028. var angle = 0;
  51029. var increment = (Math.PI * 2) / numberOfSides;
  51030. for (var i = 0; i < numberOfSides; i++) {
  51031. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  51032. angle -= increment;
  51033. }
  51034. return result;
  51035. };
  51036. Polygon.Parse = function (input) {
  51037. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  51038. var i, result = [];
  51039. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  51040. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  51041. }
  51042. return result;
  51043. };
  51044. Polygon.StartingAt = function (x, y) {
  51045. return BABYLON.Path2.StartingAt(x, y);
  51046. };
  51047. return Polygon;
  51048. }());
  51049. BABYLON.Polygon = Polygon;
  51050. var PolygonMeshBuilder = (function () {
  51051. function PolygonMeshBuilder(name, contours, scene) {
  51052. this._points = new PolygonPoints();
  51053. this._outlinepoints = new PolygonPoints();
  51054. this._holes = [];
  51055. this._epoints = new Array();
  51056. this._eholes = new Array();
  51057. this._name = name;
  51058. this._scene = scene;
  51059. var points;
  51060. if (contours instanceof BABYLON.Path2) {
  51061. points = contours.getPoints();
  51062. }
  51063. else {
  51064. points = contours;
  51065. }
  51066. this._addToepoint(points);
  51067. this._points.add(points);
  51068. this._outlinepoints.add(points);
  51069. }
  51070. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  51071. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  51072. var p = points_1[_i];
  51073. this._epoints.push(p.x, p.y);
  51074. }
  51075. };
  51076. PolygonMeshBuilder.prototype.addHole = function (hole) {
  51077. this._points.add(hole);
  51078. var holepoints = new PolygonPoints();
  51079. holepoints.add(hole);
  51080. this._holes.push(holepoints);
  51081. this._eholes.push(this._epoints.length / 2);
  51082. this._addToepoint(hole);
  51083. return this;
  51084. };
  51085. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  51086. var _this = this;
  51087. if (updatable === void 0) { updatable = false; }
  51088. var result = new BABYLON.Mesh(this._name, this._scene);
  51089. var normals = [];
  51090. var positions = [];
  51091. var uvs = [];
  51092. var bounds = this._points.computeBounds();
  51093. this._points.elements.forEach(function (p) {
  51094. normals.push(0, 1.0, 0);
  51095. positions.push(p.x, 0, p.y);
  51096. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  51097. });
  51098. var indices = [];
  51099. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  51100. for (var i = 0; i < res.length; i++) {
  51101. indices.push(res[i]);
  51102. }
  51103. if (depth > 0) {
  51104. var positionscount = (positions.length / 3); //get the current pointcount
  51105. this._points.elements.forEach(function (p) {
  51106. normals.push(0, -1.0, 0);
  51107. positions.push(p.x, -depth, p.y);
  51108. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  51109. });
  51110. var totalCount = indices.length;
  51111. for (var i = 0; i < totalCount; i += 3) {
  51112. var i0 = indices[i + 0];
  51113. var i1 = indices[i + 1];
  51114. var i2 = indices[i + 2];
  51115. indices.push(i2 + positionscount);
  51116. indices.push(i1 + positionscount);
  51117. indices.push(i0 + positionscount);
  51118. }
  51119. //Add the sides
  51120. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  51121. this._holes.forEach(function (hole) {
  51122. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  51123. });
  51124. }
  51125. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  51126. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  51127. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  51128. result.setIndices(indices);
  51129. return result;
  51130. };
  51131. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  51132. var StartIndex = positions.length / 3;
  51133. var ulength = 0;
  51134. for (var i = 0; i < points.elements.length; i++) {
  51135. var p = points.elements[i];
  51136. var p1;
  51137. if ((i + 1) > points.elements.length - 1) {
  51138. p1 = points.elements[0];
  51139. }
  51140. else {
  51141. p1 = points.elements[i + 1];
  51142. }
  51143. positions.push(p.x, 0, p.y);
  51144. positions.push(p.x, -depth, p.y);
  51145. positions.push(p1.x, 0, p1.y);
  51146. positions.push(p1.x, -depth, p1.y);
  51147. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  51148. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  51149. var v3 = v2.subtract(v1);
  51150. var v4 = new BABYLON.Vector3(0, 1, 0);
  51151. var vn = BABYLON.Vector3.Cross(v3, v4);
  51152. vn = vn.normalize();
  51153. uvs.push(ulength / bounds.width, 0);
  51154. uvs.push(ulength / bounds.width, 1);
  51155. ulength += v3.length();
  51156. uvs.push((ulength / bounds.width), 0);
  51157. uvs.push((ulength / bounds.width), 1);
  51158. if (!flip) {
  51159. normals.push(-vn.x, -vn.y, -vn.z);
  51160. normals.push(-vn.x, -vn.y, -vn.z);
  51161. normals.push(-vn.x, -vn.y, -vn.z);
  51162. normals.push(-vn.x, -vn.y, -vn.z);
  51163. indices.push(StartIndex);
  51164. indices.push(StartIndex + 1);
  51165. indices.push(StartIndex + 2);
  51166. indices.push(StartIndex + 1);
  51167. indices.push(StartIndex + 3);
  51168. indices.push(StartIndex + 2);
  51169. }
  51170. else {
  51171. normals.push(vn.x, vn.y, vn.z);
  51172. normals.push(vn.x, vn.y, vn.z);
  51173. normals.push(vn.x, vn.y, vn.z);
  51174. normals.push(vn.x, vn.y, vn.z);
  51175. indices.push(StartIndex);
  51176. indices.push(StartIndex + 2);
  51177. indices.push(StartIndex + 1);
  51178. indices.push(StartIndex + 1);
  51179. indices.push(StartIndex + 2);
  51180. indices.push(StartIndex + 3);
  51181. }
  51182. StartIndex += 4;
  51183. }
  51184. ;
  51185. };
  51186. return PolygonMeshBuilder;
  51187. }());
  51188. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  51189. })(BABYLON || (BABYLON = {}));
  51190. //# sourceMappingURL=babylon.polygonMesh.js.map
  51191. var BABYLON;
  51192. (function (BABYLON) {
  51193. var Octree = (function () {
  51194. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  51195. if (maxDepth === void 0) { maxDepth = 2; }
  51196. this.maxDepth = maxDepth;
  51197. this.dynamicContent = new Array();
  51198. this._maxBlockCapacity = maxBlockCapacity || 64;
  51199. this._selectionContent = new BABYLON.SmartArray(1024);
  51200. this._creationFunc = creationFunc;
  51201. }
  51202. // Methods
  51203. Octree.prototype.update = function (worldMin, worldMax, entries) {
  51204. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  51205. };
  51206. Octree.prototype.addMesh = function (entry) {
  51207. for (var index = 0; index < this.blocks.length; index++) {
  51208. var block = this.blocks[index];
  51209. block.addEntry(entry);
  51210. }
  51211. };
  51212. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  51213. this._selectionContent.reset();
  51214. for (var index = 0; index < this.blocks.length; index++) {
  51215. var block = this.blocks[index];
  51216. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  51217. }
  51218. if (allowDuplicate) {
  51219. this._selectionContent.concat(this.dynamicContent);
  51220. }
  51221. else {
  51222. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  51223. }
  51224. return this._selectionContent;
  51225. };
  51226. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  51227. this._selectionContent.reset();
  51228. for (var index = 0; index < this.blocks.length; index++) {
  51229. var block = this.blocks[index];
  51230. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  51231. }
  51232. if (allowDuplicate) {
  51233. this._selectionContent.concat(this.dynamicContent);
  51234. }
  51235. else {
  51236. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  51237. }
  51238. return this._selectionContent;
  51239. };
  51240. Octree.prototype.intersectsRay = function (ray) {
  51241. this._selectionContent.reset();
  51242. for (var index = 0; index < this.blocks.length; index++) {
  51243. var block = this.blocks[index];
  51244. block.intersectsRay(ray, this._selectionContent);
  51245. }
  51246. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  51247. return this._selectionContent;
  51248. };
  51249. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  51250. target.blocks = new Array();
  51251. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  51252. // Segmenting space
  51253. for (var x = 0; x < 2; x++) {
  51254. for (var y = 0; y < 2; y++) {
  51255. for (var z = 0; z < 2; z++) {
  51256. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  51257. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  51258. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  51259. block.addEntries(entries);
  51260. target.blocks.push(block);
  51261. }
  51262. }
  51263. }
  51264. };
  51265. return Octree;
  51266. }());
  51267. Octree.CreationFuncForMeshes = function (entry, block) {
  51268. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  51269. block.entries.push(entry);
  51270. }
  51271. };
  51272. Octree.CreationFuncForSubMeshes = function (entry, block) {
  51273. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  51274. block.entries.push(entry);
  51275. }
  51276. };
  51277. BABYLON.Octree = Octree;
  51278. })(BABYLON || (BABYLON = {}));
  51279. //# sourceMappingURL=babylon.octree.js.map
  51280. var BABYLON;
  51281. (function (BABYLON) {
  51282. var OctreeBlock = (function () {
  51283. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  51284. this.entries = new Array();
  51285. this._boundingVectors = new Array();
  51286. this._capacity = capacity;
  51287. this._depth = depth;
  51288. this._maxDepth = maxDepth;
  51289. this._creationFunc = creationFunc;
  51290. this._minPoint = minPoint;
  51291. this._maxPoint = maxPoint;
  51292. this._boundingVectors.push(minPoint.clone());
  51293. this._boundingVectors.push(maxPoint.clone());
  51294. this._boundingVectors.push(minPoint.clone());
  51295. this._boundingVectors[2].x = maxPoint.x;
  51296. this._boundingVectors.push(minPoint.clone());
  51297. this._boundingVectors[3].y = maxPoint.y;
  51298. this._boundingVectors.push(minPoint.clone());
  51299. this._boundingVectors[4].z = maxPoint.z;
  51300. this._boundingVectors.push(maxPoint.clone());
  51301. this._boundingVectors[5].z = minPoint.z;
  51302. this._boundingVectors.push(maxPoint.clone());
  51303. this._boundingVectors[6].x = minPoint.x;
  51304. this._boundingVectors.push(maxPoint.clone());
  51305. this._boundingVectors[7].y = minPoint.y;
  51306. }
  51307. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  51308. // Property
  51309. get: function () {
  51310. return this._capacity;
  51311. },
  51312. enumerable: true,
  51313. configurable: true
  51314. });
  51315. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  51316. get: function () {
  51317. return this._minPoint;
  51318. },
  51319. enumerable: true,
  51320. configurable: true
  51321. });
  51322. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  51323. get: function () {
  51324. return this._maxPoint;
  51325. },
  51326. enumerable: true,
  51327. configurable: true
  51328. });
  51329. // Methods
  51330. OctreeBlock.prototype.addEntry = function (entry) {
  51331. if (this.blocks) {
  51332. for (var index = 0; index < this.blocks.length; index++) {
  51333. var block = this.blocks[index];
  51334. block.addEntry(entry);
  51335. }
  51336. return;
  51337. }
  51338. this._creationFunc(entry, this);
  51339. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  51340. this.createInnerBlocks();
  51341. }
  51342. };
  51343. OctreeBlock.prototype.addEntries = function (entries) {
  51344. for (var index = 0; index < entries.length; index++) {
  51345. var mesh = entries[index];
  51346. this.addEntry(mesh);
  51347. }
  51348. };
  51349. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  51350. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  51351. if (this.blocks) {
  51352. for (var index = 0; index < this.blocks.length; index++) {
  51353. var block = this.blocks[index];
  51354. block.select(frustumPlanes, selection, allowDuplicate);
  51355. }
  51356. return;
  51357. }
  51358. if (allowDuplicate) {
  51359. selection.concat(this.entries);
  51360. }
  51361. else {
  51362. selection.concatWithNoDuplicate(this.entries);
  51363. }
  51364. }
  51365. };
  51366. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  51367. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  51368. if (this.blocks) {
  51369. for (var index = 0; index < this.blocks.length; index++) {
  51370. var block = this.blocks[index];
  51371. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  51372. }
  51373. return;
  51374. }
  51375. if (allowDuplicate) {
  51376. selection.concat(this.entries);
  51377. }
  51378. else {
  51379. selection.concatWithNoDuplicate(this.entries);
  51380. }
  51381. }
  51382. };
  51383. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  51384. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  51385. if (this.blocks) {
  51386. for (var index = 0; index < this.blocks.length; index++) {
  51387. var block = this.blocks[index];
  51388. block.intersectsRay(ray, selection);
  51389. }
  51390. return;
  51391. }
  51392. selection.concatWithNoDuplicate(this.entries);
  51393. }
  51394. };
  51395. OctreeBlock.prototype.createInnerBlocks = function () {
  51396. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  51397. };
  51398. return OctreeBlock;
  51399. }());
  51400. BABYLON.OctreeBlock = OctreeBlock;
  51401. })(BABYLON || (BABYLON = {}));
  51402. //# sourceMappingURL=babylon.octreeBlock.js.map
  51403. var BABYLON;
  51404. (function (BABYLON) {
  51405. var BlurPostProcess = (function (_super) {
  51406. __extends(BlurPostProcess, _super);
  51407. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  51408. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51409. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  51410. _this.direction = direction;
  51411. _this.blurWidth = blurWidth;
  51412. _this.onApplyObservable.add(function (effect) {
  51413. effect.setFloat2("screenSize", _this.width, _this.height);
  51414. effect.setVector2("direction", _this.direction);
  51415. effect.setFloat("blurWidth", _this.blurWidth);
  51416. });
  51417. return _this;
  51418. }
  51419. return BlurPostProcess;
  51420. }(BABYLON.PostProcess));
  51421. BABYLON.BlurPostProcess = BlurPostProcess;
  51422. })(BABYLON || (BABYLON = {}));
  51423. //# sourceMappingURL=babylon.blurPostProcess.js.map
  51424. var BABYLON;
  51425. (function (BABYLON) {
  51426. var RefractionPostProcess = (function (_super) {
  51427. __extends(RefractionPostProcess, _super);
  51428. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  51429. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  51430. _this.color = color;
  51431. _this.depth = depth;
  51432. _this.colorLevel = colorLevel;
  51433. _this.onActivateObservable.add(function (cam) {
  51434. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  51435. });
  51436. _this.onApplyObservable.add(function (effect) {
  51437. effect.setColor3("baseColor", _this.color);
  51438. effect.setFloat("depth", _this.depth);
  51439. effect.setFloat("colorLevel", _this.colorLevel);
  51440. effect.setTexture("refractionSampler", _this._refRexture);
  51441. });
  51442. return _this;
  51443. }
  51444. // Methods
  51445. RefractionPostProcess.prototype.dispose = function (camera) {
  51446. if (this._refRexture) {
  51447. this._refRexture.dispose();
  51448. }
  51449. _super.prototype.dispose.call(this, camera);
  51450. };
  51451. return RefractionPostProcess;
  51452. }(BABYLON.PostProcess));
  51453. BABYLON.RefractionPostProcess = RefractionPostProcess;
  51454. })(BABYLON || (BABYLON = {}));
  51455. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  51456. var BABYLON;
  51457. (function (BABYLON) {
  51458. var BlackAndWhitePostProcess = (function (_super) {
  51459. __extends(BlackAndWhitePostProcess, _super);
  51460. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  51461. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  51462. }
  51463. return BlackAndWhitePostProcess;
  51464. }(BABYLON.PostProcess));
  51465. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  51466. })(BABYLON || (BABYLON = {}));
  51467. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  51468. var BABYLON;
  51469. (function (BABYLON) {
  51470. var ConvolutionPostProcess = (function (_super) {
  51471. __extends(ConvolutionPostProcess, _super);
  51472. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  51473. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  51474. _this.kernel = kernel;
  51475. _this.onApply = function (effect) {
  51476. effect.setFloat2("screenSize", _this.width, _this.height);
  51477. effect.setArray("kernel", _this.kernel);
  51478. };
  51479. return _this;
  51480. }
  51481. return ConvolutionPostProcess;
  51482. }(BABYLON.PostProcess));
  51483. // Statics
  51484. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  51485. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  51486. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  51487. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  51488. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  51489. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  51490. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  51491. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  51492. })(BABYLON || (BABYLON = {}));
  51493. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  51494. var BABYLON;
  51495. (function (BABYLON) {
  51496. var FilterPostProcess = (function (_super) {
  51497. __extends(FilterPostProcess, _super);
  51498. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  51499. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  51500. _this.kernelMatrix = kernelMatrix;
  51501. _this.onApply = function (effect) {
  51502. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  51503. };
  51504. return _this;
  51505. }
  51506. return FilterPostProcess;
  51507. }(BABYLON.PostProcess));
  51508. BABYLON.FilterPostProcess = FilterPostProcess;
  51509. })(BABYLON || (BABYLON = {}));
  51510. //# sourceMappingURL=babylon.filterPostProcess.js.map
  51511. var BABYLON;
  51512. (function (BABYLON) {
  51513. var FxaaPostProcess = (function (_super) {
  51514. __extends(FxaaPostProcess, _super);
  51515. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  51516. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable) || this;
  51517. _this.onSizeChangedObservable.add(function () {
  51518. _this.texelWidth = 1.0 / _this.width;
  51519. _this.texelHeight = 1.0 / _this.height;
  51520. });
  51521. _this.onApplyObservable.add(function (effect) {
  51522. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  51523. });
  51524. return _this;
  51525. }
  51526. return FxaaPostProcess;
  51527. }(BABYLON.PostProcess));
  51528. BABYLON.FxaaPostProcess = FxaaPostProcess;
  51529. })(BABYLON || (BABYLON = {}));
  51530. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  51531. var BABYLON;
  51532. (function (BABYLON) {
  51533. var StereoscopicInterlacePostProcess = (function (_super) {
  51534. __extends(StereoscopicInterlacePostProcess, _super);
  51535. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  51536. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  51537. _this._passedProcess = rigCameras[0]._rigPostProcess;
  51538. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  51539. _this.onSizeChangedObservable.add(function () {
  51540. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  51541. });
  51542. _this.onApplyObservable.add(function (effect) {
  51543. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  51544. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  51545. });
  51546. return _this;
  51547. }
  51548. return StereoscopicInterlacePostProcess;
  51549. }(BABYLON.PostProcess));
  51550. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  51551. })(BABYLON || (BABYLON = {}));
  51552. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  51553. var BABYLON;
  51554. (function (BABYLON) {
  51555. var LensFlare = (function () {
  51556. function LensFlare(size, position, color, imgUrl, system) {
  51557. this.size = size;
  51558. this.position = position;
  51559. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  51560. this.dispose = function () {
  51561. if (this.texture) {
  51562. this.texture.dispose();
  51563. }
  51564. // Remove from scene
  51565. var index = this._system.lensFlares.indexOf(this);
  51566. this._system.lensFlares.splice(index, 1);
  51567. };
  51568. this.color = color || new BABYLON.Color3(1, 1, 1);
  51569. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  51570. this._system = system;
  51571. system.lensFlares.push(this);
  51572. }
  51573. return LensFlare;
  51574. }());
  51575. BABYLON.LensFlare = LensFlare;
  51576. })(BABYLON || (BABYLON = {}));
  51577. //# sourceMappingURL=babylon.lensFlare.js.map
  51578. var BABYLON;
  51579. (function (BABYLON) {
  51580. var LensFlareSystem = (function () {
  51581. function LensFlareSystem(name, emitter, scene) {
  51582. this.name = name;
  51583. this.lensFlares = new Array();
  51584. this.borderLimit = 300;
  51585. this.viewportBorder = 0;
  51586. this.layerMask = 0x0FFFFFFF;
  51587. this._vertexBuffers = {};
  51588. this._isEnabled = true;
  51589. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51590. this._emitter = emitter;
  51591. this.id = name;
  51592. scene.lensFlareSystems.push(this);
  51593. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  51594. var engine = scene.getEngine();
  51595. // VBO
  51596. var vertices = [];
  51597. vertices.push(1, 1);
  51598. vertices.push(-1, 1);
  51599. vertices.push(-1, -1);
  51600. vertices.push(1, -1);
  51601. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  51602. // Indices
  51603. var indices = [];
  51604. indices.push(0);
  51605. indices.push(1);
  51606. indices.push(2);
  51607. indices.push(0);
  51608. indices.push(2);
  51609. indices.push(3);
  51610. this._indexBuffer = engine.createIndexBuffer(indices);
  51611. // Effects
  51612. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  51613. }
  51614. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  51615. get: function () {
  51616. return this._isEnabled;
  51617. },
  51618. set: function (value) {
  51619. this._isEnabled = value;
  51620. },
  51621. enumerable: true,
  51622. configurable: true
  51623. });
  51624. LensFlareSystem.prototype.getScene = function () {
  51625. return this._scene;
  51626. };
  51627. LensFlareSystem.prototype.getEmitter = function () {
  51628. return this._emitter;
  51629. };
  51630. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  51631. this._emitter = newEmitter;
  51632. };
  51633. LensFlareSystem.prototype.getEmitterPosition = function () {
  51634. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  51635. };
  51636. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  51637. var position = this.getEmitterPosition();
  51638. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  51639. this._positionX = position.x;
  51640. this._positionY = position.y;
  51641. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  51642. if (this.viewportBorder > 0) {
  51643. globalViewport.x -= this.viewportBorder;
  51644. globalViewport.y -= this.viewportBorder;
  51645. globalViewport.width += this.viewportBorder * 2;
  51646. globalViewport.height += this.viewportBorder * 2;
  51647. position.x += this.viewportBorder;
  51648. position.y += this.viewportBorder;
  51649. this._positionX += this.viewportBorder;
  51650. this._positionY += this.viewportBorder;
  51651. }
  51652. if (position.z > 0) {
  51653. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  51654. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  51655. return true;
  51656. }
  51657. return true;
  51658. }
  51659. return false;
  51660. };
  51661. LensFlareSystem.prototype._isVisible = function () {
  51662. if (!this._isEnabled) {
  51663. return false;
  51664. }
  51665. var emitterPosition = this.getEmitterPosition();
  51666. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  51667. var distance = direction.length();
  51668. direction.normalize();
  51669. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  51670. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  51671. return !pickInfo.hit || pickInfo.distance > distance;
  51672. };
  51673. LensFlareSystem.prototype.render = function () {
  51674. if (!this._effect.isReady())
  51675. return false;
  51676. var engine = this._scene.getEngine();
  51677. var viewport = this._scene.activeCamera.viewport;
  51678. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  51679. // Position
  51680. if (!this.computeEffectivePosition(globalViewport)) {
  51681. return false;
  51682. }
  51683. // Visibility
  51684. if (!this._isVisible()) {
  51685. return false;
  51686. }
  51687. // Intensity
  51688. var awayX;
  51689. var awayY;
  51690. if (this._positionX < this.borderLimit + globalViewport.x) {
  51691. awayX = this.borderLimit + globalViewport.x - this._positionX;
  51692. }
  51693. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  51694. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  51695. }
  51696. else {
  51697. awayX = 0;
  51698. }
  51699. if (this._positionY < this.borderLimit + globalViewport.y) {
  51700. awayY = this.borderLimit + globalViewport.y - this._positionY;
  51701. }
  51702. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  51703. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  51704. }
  51705. else {
  51706. awayY = 0;
  51707. }
  51708. var away = (awayX > awayY) ? awayX : awayY;
  51709. away -= this.viewportBorder;
  51710. if (away > this.borderLimit) {
  51711. away = this.borderLimit;
  51712. }
  51713. var intensity = 1.0 - (away / this.borderLimit);
  51714. if (intensity < 0) {
  51715. return false;
  51716. }
  51717. if (intensity > 1.0) {
  51718. intensity = 1.0;
  51719. }
  51720. if (this.viewportBorder > 0) {
  51721. globalViewport.x += this.viewportBorder;
  51722. globalViewport.y += this.viewportBorder;
  51723. globalViewport.width -= this.viewportBorder * 2;
  51724. globalViewport.height -= this.viewportBorder * 2;
  51725. this._positionX -= this.viewportBorder;
  51726. this._positionY -= this.viewportBorder;
  51727. }
  51728. // Position
  51729. var centerX = globalViewport.x + globalViewport.width / 2;
  51730. var centerY = globalViewport.y + globalViewport.height / 2;
  51731. var distX = centerX - this._positionX;
  51732. var distY = centerY - this._positionY;
  51733. // Effects
  51734. engine.enableEffect(this._effect);
  51735. engine.setState(false);
  51736. engine.setDepthBuffer(false);
  51737. // VBOs
  51738. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  51739. // Flares
  51740. for (var index = 0; index < this.lensFlares.length; index++) {
  51741. var flare = this.lensFlares[index];
  51742. engine.setAlphaMode(flare.alphaMode);
  51743. var x = centerX - (distX * flare.position);
  51744. var y = centerY - (distY * flare.position);
  51745. var cw = flare.size;
  51746. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  51747. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  51748. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  51749. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  51750. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  51751. // Texture
  51752. this._effect.setTexture("textureSampler", flare.texture);
  51753. // Color
  51754. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  51755. // Draw order
  51756. engine.draw(true, 0, 6);
  51757. }
  51758. engine.setDepthBuffer(true);
  51759. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51760. return true;
  51761. };
  51762. LensFlareSystem.prototype.dispose = function () {
  51763. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  51764. if (vertexBuffer) {
  51765. vertexBuffer.dispose();
  51766. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  51767. }
  51768. if (this._indexBuffer) {
  51769. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51770. this._indexBuffer = null;
  51771. }
  51772. while (this.lensFlares.length) {
  51773. this.lensFlares[0].dispose();
  51774. }
  51775. // Remove from scene
  51776. var index = this._scene.lensFlareSystems.indexOf(this);
  51777. this._scene.lensFlareSystems.splice(index, 1);
  51778. };
  51779. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  51780. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  51781. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  51782. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  51783. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  51784. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  51785. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  51786. var parsedFlare = parsedLensFlareSystem.flares[index];
  51787. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  51788. }
  51789. return lensFlareSystem;
  51790. };
  51791. LensFlareSystem.prototype.serialize = function () {
  51792. var serializationObject = {};
  51793. serializationObject.id = this.id;
  51794. serializationObject.name = this.name;
  51795. serializationObject.emitterId = this.getEmitter().id;
  51796. serializationObject.borderLimit = this.borderLimit;
  51797. serializationObject.flares = [];
  51798. for (var index = 0; index < this.lensFlares.length; index++) {
  51799. var flare = this.lensFlares[index];
  51800. serializationObject.flares.push({
  51801. size: flare.size,
  51802. position: flare.position,
  51803. color: flare.color.asArray(),
  51804. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  51805. });
  51806. }
  51807. return serializationObject;
  51808. };
  51809. return LensFlareSystem;
  51810. }());
  51811. BABYLON.LensFlareSystem = LensFlareSystem;
  51812. })(BABYLON || (BABYLON = {}));
  51813. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  51814. /// <reference path="babylon.freeCamera.ts" />
  51815. var BABYLON;
  51816. (function (BABYLON) {
  51817. // We're mainly based on the logic defined into the FreeCamera code
  51818. var DeviceOrientationCamera = (function (_super) {
  51819. __extends(DeviceOrientationCamera, _super);
  51820. function DeviceOrientationCamera(name, position, scene) {
  51821. var _this = _super.call(this, name, position, scene) || this;
  51822. _this._quaternionCache = new BABYLON.Quaternion();
  51823. _this.inputs.addDeviceOrientation();
  51824. return _this;
  51825. }
  51826. DeviceOrientationCamera.prototype.getClassName = function () {
  51827. return "DeviceOrientationCamera";
  51828. };
  51829. DeviceOrientationCamera.prototype._checkInputs = function () {
  51830. _super.prototype._checkInputs.call(this);
  51831. this._quaternionCache.copyFrom(this.rotationQuaternion);
  51832. if (this._initialQuaternion) {
  51833. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  51834. }
  51835. };
  51836. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  51837. var _this = this;
  51838. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  51839. //can only work if this camera has a rotation quaternion already.
  51840. if (!this.rotationQuaternion)
  51841. return;
  51842. if (!this._initialQuaternion) {
  51843. this._initialQuaternion = new BABYLON.Quaternion();
  51844. }
  51845. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  51846. ['x', 'y', 'z'].forEach(function (axisName) {
  51847. if (!axis[axisName]) {
  51848. _this._initialQuaternion[axisName] = 0;
  51849. }
  51850. else {
  51851. _this._initialQuaternion[axisName] *= -1;
  51852. }
  51853. });
  51854. this._initialQuaternion.normalize();
  51855. //force rotation update
  51856. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  51857. };
  51858. return DeviceOrientationCamera;
  51859. }(BABYLON.FreeCamera));
  51860. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  51861. })(BABYLON || (BABYLON = {}));
  51862. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  51863. var BABYLON;
  51864. (function (BABYLON) {
  51865. var VRDeviceOrientationFreeCamera = (function (_super) {
  51866. __extends(VRDeviceOrientationFreeCamera, _super);
  51867. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  51868. if (compensateDistortion === void 0) { compensateDistortion = true; }
  51869. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  51870. var _this = _super.call(this, name, position, scene) || this;
  51871. vrCameraMetrics.compensateDistortion = compensateDistortion;
  51872. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  51873. return _this;
  51874. }
  51875. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  51876. return "VRDeviceOrientationFreeCamera";
  51877. };
  51878. return VRDeviceOrientationFreeCamera;
  51879. }(BABYLON.DeviceOrientationCamera));
  51880. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  51881. var VRDeviceOrientationGamepadCamera = (function (_super) {
  51882. __extends(VRDeviceOrientationGamepadCamera, _super);
  51883. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  51884. if (compensateDistortion === void 0) { compensateDistortion = true; }
  51885. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  51886. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  51887. _this.inputs.addGamepad();
  51888. return _this;
  51889. }
  51890. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  51891. return "VRDeviceOrientationGamepadCamera";
  51892. };
  51893. return VRDeviceOrientationGamepadCamera;
  51894. }(VRDeviceOrientationFreeCamera));
  51895. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  51896. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  51897. __extends(VRDeviceOrientationArcRotateCamera, _super);
  51898. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  51899. if (compensateDistortion === void 0) { compensateDistortion = true; }
  51900. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  51901. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  51902. vrCameraMetrics.compensateDistortion = compensateDistortion;
  51903. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  51904. _this.inputs.addVRDeviceOrientation();
  51905. return _this;
  51906. }
  51907. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  51908. return "VRDeviceOrientationArcRotateCamera";
  51909. };
  51910. return VRDeviceOrientationArcRotateCamera;
  51911. }(BABYLON.ArcRotateCamera));
  51912. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  51913. })(BABYLON || (BABYLON = {}));
  51914. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  51915. /// <reference path="babylon.touchCamera.ts" />
  51916. var BABYLON;
  51917. (function (BABYLON) {
  51918. // We're mainly based on the logic defined into the FreeCamera code
  51919. var UniversalCamera = (function (_super) {
  51920. __extends(UniversalCamera, _super);
  51921. //-- end properties for backward compatibility for inputs
  51922. function UniversalCamera(name, position, scene) {
  51923. var _this = _super.call(this, name, position, scene) || this;
  51924. _this.inputs.addGamepad();
  51925. return _this;
  51926. }
  51927. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  51928. //-- Begin properties for backward compatibility for inputs
  51929. get: function () {
  51930. var gamepad = this.inputs.attached["gamepad"];
  51931. if (gamepad)
  51932. return gamepad.gamepadAngularSensibility;
  51933. },
  51934. set: function (value) {
  51935. var gamepad = this.inputs.attached["gamepad"];
  51936. if (gamepad)
  51937. gamepad.gamepadAngularSensibility = value;
  51938. },
  51939. enumerable: true,
  51940. configurable: true
  51941. });
  51942. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  51943. get: function () {
  51944. var gamepad = this.inputs.attached["gamepad"];
  51945. if (gamepad)
  51946. return gamepad.gamepadMoveSensibility;
  51947. },
  51948. set: function (value) {
  51949. var gamepad = this.inputs.attached["gamepad"];
  51950. if (gamepad)
  51951. gamepad.gamepadMoveSensibility = value;
  51952. },
  51953. enumerable: true,
  51954. configurable: true
  51955. });
  51956. UniversalCamera.prototype.getClassName = function () {
  51957. return "UniversalCamera";
  51958. };
  51959. return UniversalCamera;
  51960. }(BABYLON.TouchCamera));
  51961. BABYLON.UniversalCamera = UniversalCamera;
  51962. })(BABYLON || (BABYLON = {}));
  51963. //# sourceMappingURL=babylon.universalCamera.js.map
  51964. var BABYLON;
  51965. (function (BABYLON) {
  51966. var Gamepads = (function () {
  51967. function Gamepads(ongamedpadconnected) {
  51968. var _this = this;
  51969. this.babylonGamepads = [];
  51970. this.oneGamepadConnected = false;
  51971. this.isMonitoring = false;
  51972. this.gamepadEventSupported = 'GamepadEvent' in window;
  51973. this.gamepadSupport = (navigator.getGamepads ||
  51974. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  51975. this._callbackGamepadConnected = ongamedpadconnected;
  51976. if (this.gamepadSupport) {
  51977. //first add already-connected gamepads
  51978. this._updateGamepadObjects();
  51979. if (this.babylonGamepads.length) {
  51980. this._startMonitoringGamepads();
  51981. }
  51982. // Checking if the gamepad connected event is supported (like in Firefox)
  51983. if (this.gamepadEventSupported) {
  51984. this._onGamepadConnectedEvent = function (evt) {
  51985. _this._onGamepadConnected(evt.gamepad);
  51986. };
  51987. this._onGamepadDisonnectedEvent = function (evt) {
  51988. _this._onGamepadDisconnected(evt);
  51989. };
  51990. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  51991. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  51992. }
  51993. else {
  51994. this._startMonitoringGamepads();
  51995. }
  51996. }
  51997. }
  51998. Gamepads.prototype.dispose = function () {
  51999. if (Gamepads.gamepadDOMInfo) {
  52000. document.body.removeChild(Gamepads.gamepadDOMInfo);
  52001. }
  52002. if (this._onGamepadConnectedEvent) {
  52003. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  52004. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  52005. this._onGamepadConnectedEvent = null;
  52006. this._onGamepadDisonnectedEvent = null;
  52007. }
  52008. };
  52009. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  52010. var newGamepad = this._addNewGamepad(gamepad);
  52011. if (this._callbackGamepadConnected)
  52012. this._callbackGamepadConnected(newGamepad);
  52013. this._startMonitoringGamepads();
  52014. };
  52015. Gamepads.prototype._addNewGamepad = function (gamepad) {
  52016. if (!this.oneGamepadConnected) {
  52017. this.oneGamepadConnected = true;
  52018. if (Gamepads.gamepadDOMInfo) {
  52019. document.body.removeChild(Gamepads.gamepadDOMInfo);
  52020. Gamepads.gamepadDOMInfo = null;
  52021. }
  52022. }
  52023. var newGamepad;
  52024. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  52025. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  52026. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  52027. }
  52028. else if (gamepad.pose) {
  52029. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  52030. }
  52031. else {
  52032. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  52033. }
  52034. this.babylonGamepads.push(newGamepad);
  52035. return newGamepad;
  52036. };
  52037. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  52038. // Remove the gamepad from the list of gamepads to monitor.
  52039. for (var i in this.babylonGamepads) {
  52040. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  52041. this.babylonGamepads.splice(+i, 1);
  52042. break;
  52043. }
  52044. }
  52045. // If no gamepads are left, stop the polling loop.
  52046. if (this.babylonGamepads.length == 0) {
  52047. this._stopMonitoringGamepads();
  52048. }
  52049. };
  52050. Gamepads.prototype._startMonitoringGamepads = function () {
  52051. if (!this.isMonitoring) {
  52052. this.isMonitoring = true;
  52053. this._checkGamepadsStatus();
  52054. }
  52055. };
  52056. Gamepads.prototype._stopMonitoringGamepads = function () {
  52057. this.isMonitoring = false;
  52058. };
  52059. Gamepads.prototype._checkGamepadsStatus = function () {
  52060. var _this = this;
  52061. // updating gamepad objects
  52062. this._updateGamepadObjects();
  52063. for (var i in this.babylonGamepads) {
  52064. this.babylonGamepads[i].update();
  52065. }
  52066. if (this.isMonitoring) {
  52067. if (window.requestAnimationFrame) {
  52068. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52069. }
  52070. else if (window.mozRequestAnimationFrame) {
  52071. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52072. }
  52073. else if (window.webkitRequestAnimationFrame) {
  52074. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52075. }
  52076. }
  52077. };
  52078. // This function is called only on Chrome, which does not yet support
  52079. // connection/disconnection events, but requires you to monitor
  52080. // an array for changes.
  52081. Gamepads.prototype._updateGamepadObjects = function () {
  52082. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  52083. for (var i = 0; i < gamepads.length; i++) {
  52084. if (gamepads[i]) {
  52085. if (!(gamepads[i].index in this.babylonGamepads)) {
  52086. var newGamepad = this._addNewGamepad(gamepads[i]);
  52087. if (this._callbackGamepadConnected) {
  52088. this._callbackGamepadConnected(newGamepad);
  52089. }
  52090. }
  52091. else {
  52092. this.babylonGamepads[i].browserGamepad = gamepads[i];
  52093. }
  52094. }
  52095. }
  52096. };
  52097. return Gamepads;
  52098. }());
  52099. BABYLON.Gamepads = Gamepads;
  52100. var StickValues = (function () {
  52101. function StickValues(x, y) {
  52102. this.x = x;
  52103. this.y = y;
  52104. }
  52105. return StickValues;
  52106. }());
  52107. BABYLON.StickValues = StickValues;
  52108. var Gamepad = (function () {
  52109. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  52110. if (leftStickX === void 0) { leftStickX = 0; }
  52111. if (leftStickY === void 0) { leftStickY = 1; }
  52112. if (rightStickX === void 0) { rightStickX = 2; }
  52113. if (rightStickY === void 0) { rightStickY = 3; }
  52114. this.id = id;
  52115. this.index = index;
  52116. this.browserGamepad = browserGamepad;
  52117. this.type = Gamepad.GAMEPAD;
  52118. this._leftStickAxisX = leftStickX;
  52119. this._leftStickAxisY = leftStickY;
  52120. this._rightStickAxisX = rightStickX;
  52121. this._rightStickAxisY = rightStickY;
  52122. if (this.browserGamepad.axes.length >= 2) {
  52123. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  52124. }
  52125. if (this.browserGamepad.axes.length >= 4) {
  52126. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  52127. }
  52128. }
  52129. Gamepad.prototype.onleftstickchanged = function (callback) {
  52130. this._onleftstickchanged = callback;
  52131. };
  52132. Gamepad.prototype.onrightstickchanged = function (callback) {
  52133. this._onrightstickchanged = callback;
  52134. };
  52135. Object.defineProperty(Gamepad.prototype, "leftStick", {
  52136. get: function () {
  52137. return this._leftStick;
  52138. },
  52139. set: function (newValues) {
  52140. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  52141. this._onleftstickchanged(newValues);
  52142. }
  52143. this._leftStick = newValues;
  52144. },
  52145. enumerable: true,
  52146. configurable: true
  52147. });
  52148. Object.defineProperty(Gamepad.prototype, "rightStick", {
  52149. get: function () {
  52150. return this._rightStick;
  52151. },
  52152. set: function (newValues) {
  52153. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  52154. this._onrightstickchanged(newValues);
  52155. }
  52156. this._rightStick = newValues;
  52157. },
  52158. enumerable: true,
  52159. configurable: true
  52160. });
  52161. Gamepad.prototype.update = function () {
  52162. if (this._leftStick) {
  52163. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  52164. }
  52165. if (this._rightStick) {
  52166. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  52167. }
  52168. };
  52169. return Gamepad;
  52170. }());
  52171. Gamepad.GAMEPAD = 0;
  52172. Gamepad.GENERIC = 1;
  52173. Gamepad.XBOX = 2;
  52174. Gamepad.POSE_ENABLED = 3;
  52175. BABYLON.Gamepad = Gamepad;
  52176. var GenericPad = (function (_super) {
  52177. __extends(GenericPad, _super);
  52178. function GenericPad(id, index, gamepad) {
  52179. var _this = _super.call(this, id, index, gamepad) || this;
  52180. _this.id = id;
  52181. _this.index = index;
  52182. _this.gamepad = gamepad;
  52183. _this.type = Gamepad.GENERIC;
  52184. _this._buttons = new Array(gamepad.buttons.length);
  52185. return _this;
  52186. }
  52187. GenericPad.prototype.onbuttondown = function (callback) {
  52188. this._onbuttondown = callback;
  52189. };
  52190. GenericPad.prototype.onbuttonup = function (callback) {
  52191. this._onbuttonup = callback;
  52192. };
  52193. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  52194. if (newValue !== currentValue) {
  52195. if (this._onbuttondown && newValue === 1) {
  52196. this._onbuttondown(buttonIndex);
  52197. }
  52198. if (this._onbuttonup && newValue === 0) {
  52199. this._onbuttonup(buttonIndex);
  52200. }
  52201. }
  52202. return newValue;
  52203. };
  52204. GenericPad.prototype.update = function () {
  52205. _super.prototype.update.call(this);
  52206. for (var index = 0; index < this._buttons.length; index++) {
  52207. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  52208. }
  52209. };
  52210. return GenericPad;
  52211. }(Gamepad));
  52212. BABYLON.GenericPad = GenericPad;
  52213. var Xbox360Button;
  52214. (function (Xbox360Button) {
  52215. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  52216. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  52217. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  52218. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  52219. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  52220. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  52221. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  52222. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  52223. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  52224. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  52225. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  52226. var Xbox360Dpad;
  52227. (function (Xbox360Dpad) {
  52228. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  52229. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  52230. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  52231. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  52232. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  52233. var Xbox360Pad = (function (_super) {
  52234. __extends(Xbox360Pad, _super);
  52235. function Xbox360Pad(id, index, gamepad, xboxOne) {
  52236. if (xboxOne === void 0) { xboxOne = false; }
  52237. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  52238. _this._leftTrigger = 0;
  52239. _this._rightTrigger = 0;
  52240. _this._buttonA = 0;
  52241. _this._buttonB = 0;
  52242. _this._buttonX = 0;
  52243. _this._buttonY = 0;
  52244. _this._buttonBack = 0;
  52245. _this._buttonStart = 0;
  52246. _this._buttonLB = 0;
  52247. _this._buttonRB = 0;
  52248. _this._buttonLeftStick = 0;
  52249. _this._buttonRightStick = 0;
  52250. _this._dPadUp = 0;
  52251. _this._dPadDown = 0;
  52252. _this._dPadLeft = 0;
  52253. _this._dPadRight = 0;
  52254. _this._isXboxOnePad = false;
  52255. _this.type = Gamepad.XBOX;
  52256. _this._isXboxOnePad = xboxOne;
  52257. return _this;
  52258. }
  52259. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  52260. this._onlefttriggerchanged = callback;
  52261. };
  52262. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  52263. this._onrighttriggerchanged = callback;
  52264. };
  52265. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  52266. get: function () {
  52267. return this._leftTrigger;
  52268. },
  52269. set: function (newValue) {
  52270. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  52271. this._onlefttriggerchanged(newValue);
  52272. }
  52273. this._leftTrigger = newValue;
  52274. },
  52275. enumerable: true,
  52276. configurable: true
  52277. });
  52278. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  52279. get: function () {
  52280. return this._rightTrigger;
  52281. },
  52282. set: function (newValue) {
  52283. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  52284. this._onrighttriggerchanged(newValue);
  52285. }
  52286. this._rightTrigger = newValue;
  52287. },
  52288. enumerable: true,
  52289. configurable: true
  52290. });
  52291. Xbox360Pad.prototype.onbuttondown = function (callback) {
  52292. this._onbuttondown = callback;
  52293. };
  52294. Xbox360Pad.prototype.onbuttonup = function (callback) {
  52295. this._onbuttonup = callback;
  52296. };
  52297. Xbox360Pad.prototype.ondpaddown = function (callback) {
  52298. this._ondpaddown = callback;
  52299. };
  52300. Xbox360Pad.prototype.ondpadup = function (callback) {
  52301. this._ondpadup = callback;
  52302. };
  52303. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  52304. if (newValue !== currentValue) {
  52305. if (this._onbuttondown && newValue === 1) {
  52306. this._onbuttondown(buttonType);
  52307. }
  52308. if (this._onbuttonup && newValue === 0) {
  52309. this._onbuttonup(buttonType);
  52310. }
  52311. }
  52312. return newValue;
  52313. };
  52314. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  52315. if (newValue !== currentValue) {
  52316. if (this._ondpaddown && newValue === 1) {
  52317. this._ondpaddown(buttonType);
  52318. }
  52319. if (this._ondpadup && newValue === 0) {
  52320. this._ondpadup(buttonType);
  52321. }
  52322. }
  52323. return newValue;
  52324. };
  52325. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  52326. get: function () {
  52327. return this._buttonA;
  52328. },
  52329. set: function (value) {
  52330. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  52331. },
  52332. enumerable: true,
  52333. configurable: true
  52334. });
  52335. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  52336. get: function () {
  52337. return this._buttonB;
  52338. },
  52339. set: function (value) {
  52340. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  52341. },
  52342. enumerable: true,
  52343. configurable: true
  52344. });
  52345. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  52346. get: function () {
  52347. return this._buttonX;
  52348. },
  52349. set: function (value) {
  52350. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  52351. },
  52352. enumerable: true,
  52353. configurable: true
  52354. });
  52355. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  52356. get: function () {
  52357. return this._buttonY;
  52358. },
  52359. set: function (value) {
  52360. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  52361. },
  52362. enumerable: true,
  52363. configurable: true
  52364. });
  52365. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  52366. get: function () {
  52367. return this._buttonStart;
  52368. },
  52369. set: function (value) {
  52370. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  52371. },
  52372. enumerable: true,
  52373. configurable: true
  52374. });
  52375. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  52376. get: function () {
  52377. return this._buttonBack;
  52378. },
  52379. set: function (value) {
  52380. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  52381. },
  52382. enumerable: true,
  52383. configurable: true
  52384. });
  52385. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  52386. get: function () {
  52387. return this._buttonLB;
  52388. },
  52389. set: function (value) {
  52390. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  52391. },
  52392. enumerable: true,
  52393. configurable: true
  52394. });
  52395. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  52396. get: function () {
  52397. return this._buttonRB;
  52398. },
  52399. set: function (value) {
  52400. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  52401. },
  52402. enumerable: true,
  52403. configurable: true
  52404. });
  52405. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  52406. get: function () {
  52407. return this._buttonLeftStick;
  52408. },
  52409. set: function (value) {
  52410. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  52411. },
  52412. enumerable: true,
  52413. configurable: true
  52414. });
  52415. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  52416. get: function () {
  52417. return this._buttonRightStick;
  52418. },
  52419. set: function (value) {
  52420. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  52421. },
  52422. enumerable: true,
  52423. configurable: true
  52424. });
  52425. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  52426. get: function () {
  52427. return this._dPadUp;
  52428. },
  52429. set: function (value) {
  52430. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  52431. },
  52432. enumerable: true,
  52433. configurable: true
  52434. });
  52435. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  52436. get: function () {
  52437. return this._dPadDown;
  52438. },
  52439. set: function (value) {
  52440. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  52441. },
  52442. enumerable: true,
  52443. configurable: true
  52444. });
  52445. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  52446. get: function () {
  52447. return this._dPadLeft;
  52448. },
  52449. set: function (value) {
  52450. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  52451. },
  52452. enumerable: true,
  52453. configurable: true
  52454. });
  52455. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  52456. get: function () {
  52457. return this._dPadRight;
  52458. },
  52459. set: function (value) {
  52460. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  52461. },
  52462. enumerable: true,
  52463. configurable: true
  52464. });
  52465. Xbox360Pad.prototype.update = function () {
  52466. _super.prototype.update.call(this);
  52467. if (this._isXboxOnePad) {
  52468. this.buttonA = this.browserGamepad.buttons[0].value;
  52469. this.buttonB = this.browserGamepad.buttons[1].value;
  52470. this.buttonX = this.browserGamepad.buttons[2].value;
  52471. this.buttonY = this.browserGamepad.buttons[3].value;
  52472. this.buttonLB = this.browserGamepad.buttons[4].value;
  52473. this.buttonRB = this.browserGamepad.buttons[5].value;
  52474. this.leftTrigger = this.browserGamepad.axes[2];
  52475. this.rightTrigger = this.browserGamepad.axes[5];
  52476. this.buttonBack = this.browserGamepad.buttons[9].value;
  52477. this.buttonStart = this.browserGamepad.buttons[8].value;
  52478. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  52479. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  52480. this.dPadUp = this.browserGamepad.buttons[11].value;
  52481. this.dPadDown = this.browserGamepad.buttons[12].value;
  52482. this.dPadLeft = this.browserGamepad.buttons[13].value;
  52483. this.dPadRight = this.browserGamepad.buttons[14].value;
  52484. }
  52485. else {
  52486. this.buttonA = this.browserGamepad.buttons[0].value;
  52487. this.buttonB = this.browserGamepad.buttons[1].value;
  52488. this.buttonX = this.browserGamepad.buttons[2].value;
  52489. this.buttonY = this.browserGamepad.buttons[3].value;
  52490. this.buttonLB = this.browserGamepad.buttons[4].value;
  52491. this.buttonRB = this.browserGamepad.buttons[5].value;
  52492. this.leftTrigger = this.browserGamepad.buttons[6].value;
  52493. this.rightTrigger = this.browserGamepad.buttons[7].value;
  52494. this.buttonBack = this.browserGamepad.buttons[8].value;
  52495. this.buttonStart = this.browserGamepad.buttons[9].value;
  52496. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  52497. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  52498. this.dPadUp = this.browserGamepad.buttons[12].value;
  52499. this.dPadDown = this.browserGamepad.buttons[13].value;
  52500. this.dPadLeft = this.browserGamepad.buttons[14].value;
  52501. this.dPadRight = this.browserGamepad.buttons[15].value;
  52502. }
  52503. };
  52504. return Xbox360Pad;
  52505. }(Gamepad));
  52506. BABYLON.Xbox360Pad = Xbox360Pad;
  52507. })(BABYLON || (BABYLON = {}));
  52508. //# sourceMappingURL=babylon.gamepads.js.map
  52509. var BABYLON;
  52510. (function (BABYLON) {
  52511. var PoseEnabledControllerType;
  52512. (function (PoseEnabledControllerType) {
  52513. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  52514. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  52515. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  52516. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  52517. var PoseEnabledControllerHelper = (function () {
  52518. function PoseEnabledControllerHelper() {
  52519. }
  52520. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  52521. // for now, only Oculus and Vive are supported
  52522. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  52523. return new OculusTouchController(vrGamepad);
  52524. }
  52525. else {
  52526. return new ViveController(vrGamepad);
  52527. }
  52528. };
  52529. return PoseEnabledControllerHelper;
  52530. }());
  52531. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  52532. var PoseEnabledController = (function (_super) {
  52533. __extends(PoseEnabledController, _super);
  52534. function PoseEnabledController(vrGamepad) {
  52535. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  52536. _this.vrGamepad = vrGamepad;
  52537. _this.deviceScaleFactor = 1;
  52538. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  52539. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  52540. _this.controllerType = PoseEnabledControllerType.GENERIC;
  52541. _this.position = BABYLON.Vector3.Zero();
  52542. _this.rotationQuaternion = new BABYLON.Quaternion();
  52543. _this.devicePosition = BABYLON.Vector3.Zero();
  52544. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  52545. _this._calculatedPosition = BABYLON.Vector3.Zero();
  52546. _this._calculatedRotation = new BABYLON.Quaternion();
  52547. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  52548. return _this;
  52549. }
  52550. PoseEnabledController.prototype.update = function () {
  52551. _super.prototype.update.call(this);
  52552. // update this device's offset position from the attached camera, if provided
  52553. //if (this._poseControlledCamera && this._poseControlledCamera.deviceScaleFactor) {
  52554. //this.position.copyFrom(this._poseControlledCamera.position);
  52555. //this.rotationQuaternion.copyFrom(this._poseControlledCamera.rotationQuaternion);
  52556. //this.deviceScaleFactor = this._poseControlledCamera.deviceScaleFactor;
  52557. //}
  52558. var pose = this.vrGamepad.pose;
  52559. this.updateFromDevice(pose);
  52560. if (this._mesh) {
  52561. this._mesh.position.copyFrom(this._calculatedPosition);
  52562. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  52563. }
  52564. };
  52565. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  52566. if (poseData) {
  52567. this.rawPose = poseData;
  52568. if (poseData.position) {
  52569. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  52570. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  52571. this.devicePosition.z *= -1;
  52572. }
  52573. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  52574. this._calculatedPosition.addInPlace(this.position);
  52575. // scale the position using the scale factor, add the device's position
  52576. /*if (this._poseControlledCamera) {
  52577. // this allows total positioning freedom - the device, the camera and the mesh can be individually controlled.
  52578. this._calculatedPosition.addInPlace(this._poseControlledCamera.position);
  52579. }*/
  52580. }
  52581. if (poseData.orientation) {
  52582. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  52583. if (this._mesh) {
  52584. if (this._mesh.getScene().useRightHandedSystem) {
  52585. this.deviceRotationQuaternion.z *= -1;
  52586. this.deviceRotationQuaternion.w *= -1;
  52587. }
  52588. else {
  52589. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  52590. }
  52591. }
  52592. // if the camera is set, rotate to the camera's rotation
  52593. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  52594. /*if (this._poseControlledCamera) {
  52595. Matrix.ScalingToRef(1, 1, 1, Tmp.Matrix[1]);
  52596. this._calculatedRotation.toRotationMatrix(Tmp.Matrix[0]);
  52597. Matrix.TranslationToRef(this._calculatedPosition.x, this._calculatedPosition.y, this._calculatedPosition.z, Tmp.Matrix[2]);
  52598. //Matrix.Identity().multiplyToRef(Tmp.Matrix[1], Tmp.Matrix[4]);
  52599. Tmp.Matrix[1].multiplyToRef(Tmp.Matrix[0], Tmp.Matrix[5]);
  52600. this._poseControlledCamera.getWorldMatrix().getTranslationToRef(Tmp.Vector3[0])
  52601. Matrix.ComposeToRef(new Vector3(this.deviceScaleFactor, this.deviceScaleFactor, this.deviceScaleFactor), this._poseControlledCamera.rotationQuaternion, Tmp.Vector3[0], Tmp.Matrix[4]);
  52602. Tmp.Matrix[5].multiplyToRef(Tmp.Matrix[2], Tmp.Matrix[1]);
  52603. Tmp.Matrix[1].multiplyToRef(Tmp.Matrix[4], Tmp.Matrix[2]);
  52604. Tmp.Matrix[2].decompose(Tmp.Vector3[0], this._calculatedRotation, this._calculatedPosition);
  52605. }*/
  52606. }
  52607. }
  52608. };
  52609. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  52610. if (this._mesh) {
  52611. this._mesh.parent = undefined;
  52612. }
  52613. this._mesh = mesh;
  52614. if (this._poseControlledCamera) {
  52615. this._mesh.parent = this._poseControlledCamera;
  52616. }
  52617. if (!this._mesh.rotationQuaternion) {
  52618. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  52619. }
  52620. };
  52621. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  52622. this._poseControlledCamera = camera;
  52623. if (this._mesh) {
  52624. this._mesh.parent = this._poseControlledCamera;
  52625. }
  52626. };
  52627. PoseEnabledController.prototype.detachMesh = function () {
  52628. this._mesh = undefined;
  52629. };
  52630. return PoseEnabledController;
  52631. }(BABYLON.Gamepad));
  52632. BABYLON.PoseEnabledController = PoseEnabledController;
  52633. var WebVRController = (function (_super) {
  52634. __extends(WebVRController, _super);
  52635. function WebVRController(vrGamepad) {
  52636. var _this = _super.call(this, vrGamepad) || this;
  52637. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  52638. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  52639. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  52640. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  52641. _this.onPadStateChangedObservable = new BABYLON.Observable();
  52642. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  52643. _this.pad = { x: 0, y: 0 };
  52644. // avoid GC, store state in a tmp object
  52645. _this._changes = {
  52646. pressChanged: false,
  52647. touchChanged: false,
  52648. valueChanged: false,
  52649. changed: false
  52650. };
  52651. _this._buttons = new Array(vrGamepad.buttons.length);
  52652. _this.hand = vrGamepad.hand;
  52653. return _this;
  52654. }
  52655. WebVRController.prototype.onButtonStateChange = function (callback) {
  52656. this._onButtonStateChange = callback;
  52657. };
  52658. WebVRController.prototype.update = function () {
  52659. _super.prototype.update.call(this);
  52660. for (var index = 0; index < this._buttons.length; index++) {
  52661. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  52662. }
  52663. ;
  52664. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  52665. this.pad.x = this.leftStick.x;
  52666. this.pad.y = this.leftStick.y;
  52667. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  52668. }
  52669. };
  52670. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  52671. if (!currentState) {
  52672. this._buttons[buttonIndex] = {
  52673. pressed: newState.pressed,
  52674. touched: newState.touched,
  52675. value: newState.value
  52676. };
  52677. return;
  52678. }
  52679. this._checkChanges(newState, currentState);
  52680. if (this._changes.changed) {
  52681. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  52682. this.handleButtonChange(buttonIndex, newState, this._changes);
  52683. }
  52684. this._buttons[buttonIndex].pressed = newState.pressed;
  52685. this._buttons[buttonIndex].touched = newState.touched;
  52686. // oculus triggers are never 0, thou not touched.
  52687. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  52688. };
  52689. WebVRController.prototype._checkChanges = function (newState, currentState) {
  52690. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  52691. this._changes.touchChanged = newState.touched !== currentState.touched;
  52692. this._changes.valueChanged = newState.value !== currentState.value;
  52693. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  52694. return this._changes;
  52695. };
  52696. return WebVRController;
  52697. }(PoseEnabledController));
  52698. BABYLON.WebVRController = WebVRController;
  52699. var OculusTouchController = (function (_super) {
  52700. __extends(OculusTouchController, _super);
  52701. function OculusTouchController(vrGamepad) {
  52702. var _this = _super.call(this, vrGamepad) || this;
  52703. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  52704. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  52705. _this.controllerType = PoseEnabledControllerType.OCULUS;
  52706. return _this;
  52707. }
  52708. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  52709. var _this = this;
  52710. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  52711. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  52712. /*
  52713. Parent Mesh name: oculus_touch_left
  52714. - body
  52715. - trigger
  52716. - thumbstick
  52717. - grip
  52718. - button_y
  52719. - button_x
  52720. - button_enter
  52721. */
  52722. _this._defaultModel = newMeshes[1];
  52723. if (meshLoaded) {
  52724. meshLoaded(_this._defaultModel);
  52725. }
  52726. _this.attachToMesh(_this._defaultModel);
  52727. });
  52728. };
  52729. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  52730. // helper getters for left and right hand.
  52731. get: function () {
  52732. if (this.hand === 'right') {
  52733. return this.onMainButtonStateChangedObservable;
  52734. }
  52735. else {
  52736. throw new Error('No A button on left hand');
  52737. }
  52738. },
  52739. enumerable: true,
  52740. configurable: true
  52741. });
  52742. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  52743. get: function () {
  52744. if (this.hand === 'right') {
  52745. return this.onSecondaryButtonStateChangedObservable;
  52746. }
  52747. else {
  52748. throw new Error('No B button on left hand');
  52749. }
  52750. },
  52751. enumerable: true,
  52752. configurable: true
  52753. });
  52754. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  52755. get: function () {
  52756. if (this.hand === 'left') {
  52757. return this.onMainButtonStateChangedObservable;
  52758. }
  52759. else {
  52760. throw new Error('No X button on right hand');
  52761. }
  52762. },
  52763. enumerable: true,
  52764. configurable: true
  52765. });
  52766. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  52767. get: function () {
  52768. if (this.hand === 'left') {
  52769. return this.onSecondaryButtonStateChangedObservable;
  52770. }
  52771. else {
  52772. throw new Error('No Y button on right hand');
  52773. }
  52774. },
  52775. enumerable: true,
  52776. configurable: true
  52777. });
  52778. /*
  52779. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  52780. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  52781. 2) secondary trigger (same)
  52782. 3) A (right) X (left), touch, pressed = value
  52783. 4) B / Y
  52784. 5) thumb rest
  52785. */
  52786. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52787. var notifyObject = state; //{ state: state, changes: changes };
  52788. switch (buttonIdx) {
  52789. case 0:
  52790. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  52791. return;
  52792. case 1:
  52793. if (this._defaultModel) {
  52794. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  52795. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  52796. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  52797. }
  52798. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  52799. return;
  52800. case 2:
  52801. if (this._defaultModel) {
  52802. (this._defaultModel.getChildren()[4]).position.x = notifyObject.value * 0.0035;
  52803. }
  52804. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  52805. return;
  52806. case 3:
  52807. if (this._defaultModel) {
  52808. if (notifyObject.pressed) {
  52809. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  52810. }
  52811. else {
  52812. (this._defaultModel.getChildren()[1]).position.y = 0;
  52813. }
  52814. }
  52815. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  52816. return;
  52817. case 4:
  52818. if (this._defaultModel) {
  52819. if (notifyObject.pressed) {
  52820. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  52821. }
  52822. else {
  52823. (this._defaultModel.getChildren()[2]).position.y = 0;
  52824. }
  52825. }
  52826. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  52827. return;
  52828. case 5:
  52829. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  52830. return;
  52831. }
  52832. };
  52833. return OculusTouchController;
  52834. }(WebVRController));
  52835. BABYLON.OculusTouchController = OculusTouchController;
  52836. var ViveController = (function (_super) {
  52837. __extends(ViveController, _super);
  52838. function ViveController(vrGamepad) {
  52839. var _this = _super.call(this, vrGamepad) || this;
  52840. _this.controllerType = PoseEnabledControllerType.VIVE;
  52841. return _this;
  52842. }
  52843. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  52844. var _this = this;
  52845. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  52846. /*
  52847. Parent Mesh name: ViveWand
  52848. - body
  52849. - r_gripper
  52850. - l_gripper
  52851. - menu_button
  52852. - system_button
  52853. - trackpad
  52854. - trigger
  52855. - LED
  52856. */
  52857. _this._defaultModel = newMeshes[1];
  52858. if (meshLoaded) {
  52859. meshLoaded(_this._defaultModel);
  52860. }
  52861. _this.attachToMesh(_this._defaultModel);
  52862. });
  52863. };
  52864. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  52865. get: function () {
  52866. return this.onMainButtonStateChangedObservable;
  52867. },
  52868. enumerable: true,
  52869. configurable: true
  52870. });
  52871. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  52872. get: function () {
  52873. return this.onMainButtonStateChangedObservable;
  52874. },
  52875. enumerable: true,
  52876. configurable: true
  52877. });
  52878. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  52879. get: function () {
  52880. return this.onSecondaryButtonStateChangedObservable;
  52881. },
  52882. enumerable: true,
  52883. configurable: true
  52884. });
  52885. /**
  52886. * Vive mapping:
  52887. * 0: touchpad
  52888. * 1: trigger
  52889. * 2: left AND right buttons
  52890. * 3: menu button
  52891. */
  52892. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52893. var notifyObject = state; //{ state: state, changes: changes };
  52894. switch (buttonIdx) {
  52895. case 0:
  52896. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  52897. return;
  52898. case 1:
  52899. if (this._defaultModel) {
  52900. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  52901. }
  52902. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  52903. return;
  52904. case 2:
  52905. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  52906. return;
  52907. case 3:
  52908. if (this._defaultModel) {
  52909. if (notifyObject.pressed) {
  52910. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  52911. }
  52912. else {
  52913. (this._defaultModel.getChildren()[2]).position.y = 0;
  52914. }
  52915. }
  52916. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  52917. return;
  52918. }
  52919. };
  52920. return ViveController;
  52921. }(WebVRController));
  52922. BABYLON.ViveController = ViveController;
  52923. })(BABYLON || (BABYLON = {}));
  52924. //# sourceMappingURL=babylon.extendedGamepad.js.map
  52925. /// <reference path="babylon.universalCamera.ts" />
  52926. var BABYLON;
  52927. (function (BABYLON) {
  52928. // We're mainly based on the logic defined into the FreeCamera code
  52929. var GamepadCamera = (function (_super) {
  52930. __extends(GamepadCamera, _super);
  52931. //-- end properties for backward compatibility for inputs
  52932. function GamepadCamera(name, position, scene) {
  52933. return _super.call(this, name, position, scene) || this;
  52934. }
  52935. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  52936. //-- Begin properties for backward compatibility for inputs
  52937. get: function () {
  52938. var gamepad = this.inputs.attached["gamepad"];
  52939. if (gamepad)
  52940. return gamepad.gamepadAngularSensibility;
  52941. },
  52942. set: function (value) {
  52943. var gamepad = this.inputs.attached["gamepad"];
  52944. if (gamepad)
  52945. gamepad.gamepadAngularSensibility = value;
  52946. },
  52947. enumerable: true,
  52948. configurable: true
  52949. });
  52950. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  52951. get: function () {
  52952. var gamepad = this.inputs.attached["gamepad"];
  52953. if (gamepad)
  52954. return gamepad.gamepadMoveSensibility;
  52955. },
  52956. set: function (value) {
  52957. var gamepad = this.inputs.attached["gamepad"];
  52958. if (gamepad)
  52959. gamepad.gamepadMoveSensibility = value;
  52960. },
  52961. enumerable: true,
  52962. configurable: true
  52963. });
  52964. GamepadCamera.prototype.getClassName = function () {
  52965. return "GamepadCamera";
  52966. };
  52967. return GamepadCamera;
  52968. }(BABYLON.UniversalCamera));
  52969. BABYLON.GamepadCamera = GamepadCamera;
  52970. })(BABYLON || (BABYLON = {}));
  52971. //# sourceMappingURL=babylon.gamepadCamera.js.map
  52972. var BABYLON;
  52973. (function (BABYLON) {
  52974. var Analyser = (function () {
  52975. function Analyser(scene) {
  52976. this.SMOOTHING = 0.75;
  52977. this.FFT_SIZE = 512;
  52978. this.BARGRAPHAMPLITUDE = 256;
  52979. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  52980. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  52981. this._scene = scene;
  52982. this._audioEngine = BABYLON.Engine.audioEngine;
  52983. if (this._audioEngine.canUseWebAudio) {
  52984. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  52985. this._webAudioAnalyser.minDecibels = -140;
  52986. this._webAudioAnalyser.maxDecibels = 0;
  52987. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  52988. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  52989. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  52990. }
  52991. }
  52992. Analyser.prototype.getFrequencyBinCount = function () {
  52993. if (this._audioEngine.canUseWebAudio) {
  52994. return this._webAudioAnalyser.frequencyBinCount;
  52995. }
  52996. else {
  52997. return 0;
  52998. }
  52999. };
  53000. Analyser.prototype.getByteFrequencyData = function () {
  53001. if (this._audioEngine.canUseWebAudio) {
  53002. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53003. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53004. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  53005. }
  53006. return this._byteFreqs;
  53007. };
  53008. Analyser.prototype.getByteTimeDomainData = function () {
  53009. if (this._audioEngine.canUseWebAudio) {
  53010. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53011. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53012. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  53013. }
  53014. return this._byteTime;
  53015. };
  53016. Analyser.prototype.getFloatFrequencyData = function () {
  53017. if (this._audioEngine.canUseWebAudio) {
  53018. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53019. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53020. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  53021. }
  53022. return this._floatFreqs;
  53023. };
  53024. Analyser.prototype.drawDebugCanvas = function () {
  53025. var _this = this;
  53026. if (this._audioEngine.canUseWebAudio) {
  53027. if (!this._debugCanvas) {
  53028. this._debugCanvas = document.createElement("canvas");
  53029. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  53030. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  53031. this._debugCanvas.style.position = "absolute";
  53032. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  53033. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  53034. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  53035. document.body.appendChild(this._debugCanvas);
  53036. this._registerFunc = function () {
  53037. _this.drawDebugCanvas();
  53038. };
  53039. this._scene.registerBeforeRender(this._registerFunc);
  53040. }
  53041. if (this._registerFunc) {
  53042. var workingArray = this.getByteFrequencyData();
  53043. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  53044. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  53045. // Draw the frequency domain chart.
  53046. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  53047. var value = workingArray[i];
  53048. var percent = value / this.BARGRAPHAMPLITUDE;
  53049. var height = this.DEBUGCANVASSIZE.height * percent;
  53050. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  53051. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  53052. var hue = i / this.getFrequencyBinCount() * 360;
  53053. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  53054. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  53055. }
  53056. }
  53057. }
  53058. };
  53059. Analyser.prototype.stopDebugCanvas = function () {
  53060. if (this._debugCanvas) {
  53061. this._scene.unregisterBeforeRender(this._registerFunc);
  53062. this._registerFunc = null;
  53063. document.body.removeChild(this._debugCanvas);
  53064. this._debugCanvas = null;
  53065. this._debugCanvasContext = null;
  53066. }
  53067. };
  53068. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  53069. if (this._audioEngine.canUseWebAudio) {
  53070. inputAudioNode.connect(this._webAudioAnalyser);
  53071. this._webAudioAnalyser.connect(outputAudioNode);
  53072. }
  53073. };
  53074. Analyser.prototype.dispose = function () {
  53075. if (this._audioEngine.canUseWebAudio) {
  53076. this._webAudioAnalyser.disconnect();
  53077. }
  53078. };
  53079. return Analyser;
  53080. }());
  53081. BABYLON.Analyser = Analyser;
  53082. })(BABYLON || (BABYLON = {}));
  53083. //# sourceMappingURL=babylon.analyser.js.map
  53084. var BABYLON;
  53085. (function (BABYLON) {
  53086. var DepthRenderer = (function () {
  53087. function DepthRenderer(scene, type) {
  53088. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  53089. var _this = this;
  53090. this._viewMatrix = BABYLON.Matrix.Zero();
  53091. this._projectionMatrix = BABYLON.Matrix.Zero();
  53092. this._transformMatrix = BABYLON.Matrix.Zero();
  53093. this._worldViewProjection = BABYLON.Matrix.Zero();
  53094. this._scene = scene;
  53095. var engine = scene.getEngine();
  53096. // Render target
  53097. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  53098. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53099. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53100. this._depthMap.refreshRate = 1;
  53101. this._depthMap.renderParticles = false;
  53102. this._depthMap.renderList = null;
  53103. // set default depth value to 1.0 (far away)
  53104. this._depthMap.onClearObservable.add(function (engine) {
  53105. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  53106. });
  53107. // Custom render function
  53108. var renderSubMesh = function (subMesh) {
  53109. var mesh = subMesh.getRenderingMesh();
  53110. var scene = _this._scene;
  53111. var engine = scene.getEngine();
  53112. // Culling
  53113. engine.setState(subMesh.getMaterial().backFaceCulling);
  53114. // Managing instances
  53115. var batch = mesh._getInstancesRenderList(subMesh._id);
  53116. if (batch.mustReturn) {
  53117. return;
  53118. }
  53119. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  53120. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53121. engine.enableEffect(_this._effect);
  53122. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  53123. var material = subMesh.getMaterial();
  53124. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53125. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  53126. // Alpha test
  53127. if (material && material.needAlphaTesting()) {
  53128. var alphaTexture = material.getAlphaTestTexture();
  53129. _this._effect.setTexture("diffuseSampler", alphaTexture);
  53130. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53131. }
  53132. // Bones
  53133. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53134. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53135. }
  53136. // Draw
  53137. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53138. }
  53139. };
  53140. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  53141. var index;
  53142. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53143. renderSubMesh(opaqueSubMeshes.data[index]);
  53144. }
  53145. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53146. renderSubMesh(alphaTestSubMeshes.data[index]);
  53147. }
  53148. };
  53149. }
  53150. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  53151. var material = subMesh.getMaterial();
  53152. if (material.disableDepthWrite) {
  53153. return false;
  53154. }
  53155. var defines = [];
  53156. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53157. var mesh = subMesh.getMesh();
  53158. var scene = mesh.getScene();
  53159. // Alpha test
  53160. if (material && material.needAlphaTesting()) {
  53161. defines.push("#define ALPHATEST");
  53162. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53163. attribs.push(BABYLON.VertexBuffer.UVKind);
  53164. defines.push("#define UV1");
  53165. }
  53166. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53167. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53168. defines.push("#define UV2");
  53169. }
  53170. }
  53171. // Bones
  53172. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53173. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53174. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53175. if (mesh.numBoneInfluencers > 4) {
  53176. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53177. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53178. }
  53179. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53180. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53181. }
  53182. else {
  53183. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53184. }
  53185. // Instances
  53186. if (useInstances) {
  53187. defines.push("#define INSTANCES");
  53188. attribs.push("world0");
  53189. attribs.push("world1");
  53190. attribs.push("world2");
  53191. attribs.push("world3");
  53192. }
  53193. // Get correct effect
  53194. var join = defines.join("\n");
  53195. if (this._cachedDefines !== join) {
  53196. this._cachedDefines = join;
  53197. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  53198. }
  53199. return this._effect.isReady();
  53200. };
  53201. DepthRenderer.prototype.getDepthMap = function () {
  53202. return this._depthMap;
  53203. };
  53204. // Methods
  53205. DepthRenderer.prototype.dispose = function () {
  53206. this._depthMap.dispose();
  53207. };
  53208. return DepthRenderer;
  53209. }());
  53210. BABYLON.DepthRenderer = DepthRenderer;
  53211. })(BABYLON || (BABYLON = {}));
  53212. //# sourceMappingURL=babylon.depthRenderer.js.map
  53213. var BABYLON;
  53214. (function (BABYLON) {
  53215. var SSAORenderingPipeline = (function (_super) {
  53216. __extends(SSAORenderingPipeline, _super);
  53217. /**
  53218. * @constructor
  53219. * @param {string} name - The rendering pipeline name
  53220. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53221. * @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 }
  53222. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53223. */
  53224. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  53225. var _this = _super.call(this, scene.getEngine(), name) || this;
  53226. // Members
  53227. /**
  53228. * The PassPostProcess id in the pipeline that contains the original scene color
  53229. * @type {string}
  53230. */
  53231. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  53232. /**
  53233. * The SSAO PostProcess id in the pipeline
  53234. * @type {string}
  53235. */
  53236. _this.SSAORenderEffect = "SSAORenderEffect";
  53237. /**
  53238. * The horizontal blur PostProcess id in the pipeline
  53239. * @type {string}
  53240. */
  53241. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  53242. /**
  53243. * The vertical blur PostProcess id in the pipeline
  53244. * @type {string}
  53245. */
  53246. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  53247. /**
  53248. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  53249. * @type {string}
  53250. */
  53251. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  53252. /**
  53253. * The output strength of the SSAO post-process. Default value is 1.0.
  53254. * @type {number}
  53255. */
  53256. _this.totalStrength = 1.0;
  53257. /**
  53258. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  53259. * @type {number}
  53260. */
  53261. _this.radius = 0.0001;
  53262. /**
  53263. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  53264. * Must not be equal to fallOff and superior to fallOff.
  53265. * Default value is 0.975
  53266. * @type {number}
  53267. */
  53268. _this.area = 0.0075;
  53269. /**
  53270. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  53271. * Must not be equal to area and inferior to area.
  53272. * Default value is 0.0
  53273. * @type {number}
  53274. */
  53275. _this.fallOff = 0.000001;
  53276. /**
  53277. * The base color of the SSAO post-process
  53278. * The final result is "base + ssao" between [0, 1]
  53279. * @type {number}
  53280. */
  53281. _this.base = 0.5;
  53282. _this._firstUpdate = true;
  53283. _this._scene = scene;
  53284. // Set up assets
  53285. _this._createRandomTexture();
  53286. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  53287. var ssaoRatio = ratio.ssaoRatio || ratio;
  53288. var combineRatio = ratio.combineRatio || ratio;
  53289. _this._ratio = {
  53290. ssaoRatio: ssaoRatio,
  53291. combineRatio: combineRatio
  53292. };
  53293. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53294. _this._createSSAOPostProcess(ssaoRatio);
  53295. _this._createBlurPostProcess(ssaoRatio);
  53296. _this._createSSAOCombinePostProcess(combineRatio);
  53297. // Set up pipeline
  53298. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  53299. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  53300. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  53301. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  53302. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  53303. // Finish
  53304. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53305. if (cameras)
  53306. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53307. return _this;
  53308. }
  53309. // Public Methods
  53310. /**
  53311. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  53312. */
  53313. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53314. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53315. for (var i = 0; i < this._scene.cameras.length; i++) {
  53316. var camera = this._scene.cameras[i];
  53317. this._originalColorPostProcess.dispose(camera);
  53318. this._ssaoPostProcess.dispose(camera);
  53319. this._blurHPostProcess.dispose(camera);
  53320. this._blurVPostProcess.dispose(camera);
  53321. this._ssaoCombinePostProcess.dispose(camera);
  53322. }
  53323. this._randomTexture.dispose();
  53324. if (disableDepthRender)
  53325. this._scene.disableDepthRenderer();
  53326. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53327. _super.prototype.dispose.call(this);
  53328. };
  53329. // Private Methods
  53330. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  53331. var _this = this;
  53332. /*
  53333. var samplerOffsets = [
  53334. -8.0, -6.0, -4.0, -2.0,
  53335. 0.0,
  53336. 2.0, 4.0, 6.0, 8.0
  53337. ];
  53338. */
  53339. var samples = 16;
  53340. var samplerOffsets = [];
  53341. for (var i = -8; i < 8; i++) {
  53342. samplerOffsets.push(i * 2);
  53343. }
  53344. 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");
  53345. this._blurHPostProcess.onApply = function (effect) {
  53346. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  53347. effect.setTexture("depthSampler", _this._depthTexture);
  53348. if (_this._firstUpdate) {
  53349. effect.setArray("samplerOffsets", samplerOffsets);
  53350. }
  53351. };
  53352. 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");
  53353. this._blurVPostProcess.onApply = function (effect) {
  53354. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  53355. effect.setTexture("depthSampler", _this._depthTexture);
  53356. if (_this._firstUpdate) {
  53357. effect.setArray("samplerOffsets", samplerOffsets);
  53358. _this._firstUpdate = false;
  53359. }
  53360. };
  53361. };
  53362. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  53363. var _this = this;
  53364. var numSamples = 16;
  53365. var sampleSphere = [
  53366. 0.5381, 0.1856, -0.4319,
  53367. 0.1379, 0.2486, 0.4430,
  53368. 0.3371, 0.5679, -0.0057,
  53369. -0.6999, -0.0451, -0.0019,
  53370. 0.0689, -0.1598, -0.8547,
  53371. 0.0560, 0.0069, -0.1843,
  53372. -0.0146, 0.1402, 0.0762,
  53373. 0.0100, -0.1924, -0.0344,
  53374. -0.3577, -0.5301, -0.4358,
  53375. -0.3169, 0.1063, 0.0158,
  53376. 0.0103, -0.5869, 0.0046,
  53377. -0.0897, -0.4940, 0.3287,
  53378. 0.7119, -0.0154, -0.0918,
  53379. -0.0533, 0.0596, -0.5411,
  53380. 0.0352, -0.0631, 0.5460,
  53381. -0.4776, 0.2847, -0.0271
  53382. ];
  53383. var samplesFactor = 1.0 / numSamples;
  53384. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  53385. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  53386. "area", "fallOff", "base", "range", "viewport"
  53387. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  53388. var viewport = new BABYLON.Vector2(0, 0);
  53389. this._ssaoPostProcess.onApply = function (effect) {
  53390. if (_this._firstUpdate) {
  53391. effect.setArray3("sampleSphere", sampleSphere);
  53392. effect.setFloat("samplesFactor", samplesFactor);
  53393. effect.setFloat("randTextureTiles", 4.0);
  53394. }
  53395. effect.setFloat("totalStrength", _this.totalStrength);
  53396. effect.setFloat("radius", _this.radius);
  53397. effect.setFloat("area", _this.area);
  53398. effect.setFloat("fallOff", _this.fallOff);
  53399. effect.setFloat("base", _this.base);
  53400. effect.setTexture("textureSampler", _this._depthTexture);
  53401. effect.setTexture("randomSampler", _this._randomTexture);
  53402. };
  53403. };
  53404. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  53405. var _this = this;
  53406. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53407. this._ssaoCombinePostProcess.onApply = function (effect) {
  53408. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  53409. };
  53410. };
  53411. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  53412. var size = 512;
  53413. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53414. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53415. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53416. var context = this._randomTexture.getContext();
  53417. var rand = function (min, max) {
  53418. return Math.random() * (max - min) + min;
  53419. };
  53420. var randVector = BABYLON.Vector3.Zero();
  53421. for (var x = 0; x < size; x++) {
  53422. for (var y = 0; y < size; y++) {
  53423. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  53424. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  53425. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  53426. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  53427. context.fillRect(x, y, 1, 1);
  53428. }
  53429. }
  53430. this._randomTexture.update(false);
  53431. };
  53432. return SSAORenderingPipeline;
  53433. }(BABYLON.PostProcessRenderPipeline));
  53434. __decorate([
  53435. BABYLON.serialize()
  53436. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  53437. __decorate([
  53438. BABYLON.serialize()
  53439. ], SSAORenderingPipeline.prototype, "radius", void 0);
  53440. __decorate([
  53441. BABYLON.serialize()
  53442. ], SSAORenderingPipeline.prototype, "area", void 0);
  53443. __decorate([
  53444. BABYLON.serialize()
  53445. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  53446. __decorate([
  53447. BABYLON.serialize()
  53448. ], SSAORenderingPipeline.prototype, "base", void 0);
  53449. __decorate([
  53450. BABYLON.serialize()
  53451. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  53452. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  53453. })(BABYLON || (BABYLON = {}));
  53454. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  53455. var BABYLON;
  53456. (function (BABYLON) {
  53457. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  53458. var VolumetricLightScatteringPostProcess = (function (_super) {
  53459. __extends(VolumetricLightScatteringPostProcess, _super);
  53460. /**
  53461. * @constructor
  53462. * @param {string} name - The post-process name
  53463. * @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)
  53464. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  53465. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  53466. * @param {number} samples - The post-process quality, default 100
  53467. * @param {number} samplingMode - The post-process filtering mode
  53468. * @param {BABYLON.Engine} engine - The babylon engine
  53469. * @param {boolean} reusable - If the post-process is reusable
  53470. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  53471. */
  53472. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  53473. if (samples === void 0) { samples = 100; }
  53474. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53475. 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;
  53476. _this._screenCoordinates = BABYLON.Vector2.Zero();
  53477. /**
  53478. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  53479. * @type {Vector3}
  53480. */
  53481. _this.customMeshPosition = BABYLON.Vector3.Zero();
  53482. /**
  53483. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  53484. * @type {boolean}
  53485. */
  53486. _this.useCustomMeshPosition = false;
  53487. /**
  53488. * If the post-process should inverse the light scattering direction
  53489. * @type {boolean}
  53490. */
  53491. _this.invert = true;
  53492. /**
  53493. * Array containing the excluded meshes not rendered in the internal pass
  53494. */
  53495. _this.excludedMeshes = new Array();
  53496. /**
  53497. * Controls the overall intensity of the post-process
  53498. * @type {number}
  53499. */
  53500. _this.exposure = 0.3;
  53501. /**
  53502. * Dissipates each sample's contribution in range [0, 1]
  53503. * @type {number}
  53504. */
  53505. _this.decay = 0.96815;
  53506. /**
  53507. * Controls the overall intensity of each sample
  53508. * @type {number}
  53509. */
  53510. _this.weight = 0.58767;
  53511. /**
  53512. * Controls the density of each sample
  53513. * @type {number}
  53514. */
  53515. _this.density = 0.926;
  53516. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  53517. var engine = scene.getEngine();
  53518. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  53519. // Configure mesh
  53520. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  53521. // Configure
  53522. _this._createPass(scene, ratio.passRatio || ratio);
  53523. _this.onActivate = function (camera) {
  53524. if (!_this.isSupported) {
  53525. _this.dispose(camera);
  53526. }
  53527. _this.onActivate = null;
  53528. };
  53529. _this.onApplyObservable.add(function (effect) {
  53530. _this._updateMeshScreenCoordinates(scene);
  53531. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  53532. effect.setFloat("exposure", _this.exposure);
  53533. effect.setFloat("decay", _this.decay);
  53534. effect.setFloat("weight", _this.weight);
  53535. effect.setFloat("density", _this.density);
  53536. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  53537. });
  53538. return _this;
  53539. }
  53540. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  53541. get: function () {
  53542. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  53543. return false;
  53544. },
  53545. set: function (useDiffuseColor) {
  53546. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  53547. },
  53548. enumerable: true,
  53549. configurable: true
  53550. });
  53551. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  53552. var mesh = subMesh.getMesh();
  53553. // Render this.mesh as default
  53554. if (mesh === this.mesh) {
  53555. return mesh.material.isReady(mesh);
  53556. }
  53557. var defines = [];
  53558. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53559. var material = subMesh.getMaterial();
  53560. var needUV = false;
  53561. // Alpha test
  53562. if (material) {
  53563. if (material.needAlphaTesting()) {
  53564. defines.push("#define ALPHATEST");
  53565. }
  53566. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53567. attribs.push(BABYLON.VertexBuffer.UVKind);
  53568. defines.push("#define UV1");
  53569. }
  53570. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53571. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53572. defines.push("#define UV2");
  53573. }
  53574. }
  53575. // Bones
  53576. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53577. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53578. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53579. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53580. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53581. }
  53582. else {
  53583. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53584. }
  53585. // Instances
  53586. if (useInstances) {
  53587. defines.push("#define INSTANCES");
  53588. attribs.push("world0");
  53589. attribs.push("world1");
  53590. attribs.push("world2");
  53591. attribs.push("world3");
  53592. }
  53593. // Get correct effect
  53594. var join = defines.join("\n");
  53595. if (this._cachedDefines !== join) {
  53596. this._cachedDefines = join;
  53597. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  53598. }
  53599. return this._volumetricLightScatteringPass.isReady();
  53600. };
  53601. /**
  53602. * Sets the new light position for light scattering effect
  53603. * @param {BABYLON.Vector3} The new custom light position
  53604. */
  53605. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  53606. this.customMeshPosition = position;
  53607. };
  53608. /**
  53609. * Returns the light position for light scattering effect
  53610. * @return {BABYLON.Vector3} The custom light position
  53611. */
  53612. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  53613. return this.customMeshPosition;
  53614. };
  53615. /**
  53616. * Disposes the internal assets and detaches the post-process from the camera
  53617. */
  53618. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  53619. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  53620. if (rttIndex !== -1) {
  53621. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  53622. }
  53623. this._volumetricLightScatteringRTT.dispose();
  53624. _super.prototype.dispose.call(this, camera);
  53625. };
  53626. /**
  53627. * Returns the render target texture used by the post-process
  53628. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  53629. */
  53630. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  53631. return this._volumetricLightScatteringRTT;
  53632. };
  53633. // Private methods
  53634. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  53635. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  53636. return true;
  53637. }
  53638. return false;
  53639. };
  53640. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  53641. var _this = this;
  53642. var engine = scene.getEngine();
  53643. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53644. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53645. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53646. this._volumetricLightScatteringRTT.renderList = null;
  53647. this._volumetricLightScatteringRTT.renderParticles = false;
  53648. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  53649. // Custom render function for submeshes
  53650. var renderSubMesh = function (subMesh) {
  53651. var mesh = subMesh.getRenderingMesh();
  53652. if (_this._meshExcluded(mesh)) {
  53653. return;
  53654. }
  53655. var scene = mesh.getScene();
  53656. var engine = scene.getEngine();
  53657. // Culling
  53658. engine.setState(subMesh.getMaterial().backFaceCulling);
  53659. // Managing instances
  53660. var batch = mesh._getInstancesRenderList(subMesh._id);
  53661. if (batch.mustReturn) {
  53662. return;
  53663. }
  53664. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  53665. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53666. var effect = _this._volumetricLightScatteringPass;
  53667. if (mesh === _this.mesh) {
  53668. if (subMesh.effect) {
  53669. effect = subMesh.effect;
  53670. }
  53671. else {
  53672. effect = subMesh.getMaterial().getEffect();
  53673. }
  53674. }
  53675. engine.enableEffect(effect);
  53676. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  53677. if (mesh === _this.mesh) {
  53678. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  53679. }
  53680. else {
  53681. var material = subMesh.getMaterial();
  53682. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  53683. // Alpha test
  53684. if (material && material.needAlphaTesting()) {
  53685. var alphaTexture = material.getAlphaTestTexture();
  53686. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  53687. if (alphaTexture) {
  53688. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53689. }
  53690. }
  53691. // Bones
  53692. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53693. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53694. }
  53695. }
  53696. // Draw
  53697. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  53698. }
  53699. };
  53700. // Render target texture callbacks
  53701. var savedSceneClearColor;
  53702. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  53703. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  53704. savedSceneClearColor = scene.clearColor;
  53705. scene.clearColor = sceneClearColor;
  53706. });
  53707. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  53708. scene.clearColor = savedSceneClearColor;
  53709. });
  53710. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  53711. var engine = scene.getEngine();
  53712. var index;
  53713. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53714. renderSubMesh(opaqueSubMeshes.data[index]);
  53715. }
  53716. engine.setAlphaTesting(true);
  53717. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53718. renderSubMesh(alphaTestSubMeshes.data[index]);
  53719. }
  53720. engine.setAlphaTesting(false);
  53721. if (transparentSubMeshes.length) {
  53722. // Sort sub meshes
  53723. for (index = 0; index < transparentSubMeshes.length; index++) {
  53724. var submesh = transparentSubMeshes.data[index];
  53725. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  53726. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  53727. }
  53728. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  53729. sortedArray.sort(function (a, b) {
  53730. // Alpha index first
  53731. if (a._alphaIndex > b._alphaIndex) {
  53732. return 1;
  53733. }
  53734. if (a._alphaIndex < b._alphaIndex) {
  53735. return -1;
  53736. }
  53737. // Then distance to camera
  53738. if (a._distanceToCamera < b._distanceToCamera) {
  53739. return 1;
  53740. }
  53741. if (a._distanceToCamera > b._distanceToCamera) {
  53742. return -1;
  53743. }
  53744. return 0;
  53745. });
  53746. // Render sub meshes
  53747. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53748. for (index = 0; index < sortedArray.length; index++) {
  53749. renderSubMesh(sortedArray[index]);
  53750. }
  53751. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53752. }
  53753. };
  53754. };
  53755. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  53756. var transform = scene.getTransformMatrix();
  53757. var meshPosition;
  53758. if (this.useCustomMeshPosition) {
  53759. meshPosition = this.customMeshPosition;
  53760. }
  53761. else if (this.attachedNode) {
  53762. meshPosition = this.attachedNode.position;
  53763. }
  53764. else {
  53765. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  53766. }
  53767. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  53768. this._screenCoordinates.x = pos.x / this._viewPort.width;
  53769. this._screenCoordinates.y = pos.y / this._viewPort.height;
  53770. if (this.invert)
  53771. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  53772. };
  53773. // Static methods
  53774. /**
  53775. * Creates a default mesh for the Volumeric Light Scattering post-process
  53776. * @param {string} The mesh name
  53777. * @param {BABYLON.Scene} The scene where to create the mesh
  53778. * @return {BABYLON.Mesh} the default mesh
  53779. */
  53780. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  53781. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  53782. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  53783. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  53784. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  53785. mesh.material = material;
  53786. return mesh;
  53787. };
  53788. return VolumetricLightScatteringPostProcess;
  53789. }(BABYLON.PostProcess));
  53790. __decorate([
  53791. BABYLON.serializeAsVector3()
  53792. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  53793. __decorate([
  53794. BABYLON.serialize()
  53795. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  53796. __decorate([
  53797. BABYLON.serialize()
  53798. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  53799. __decorate([
  53800. BABYLON.serializeAsMeshReference()
  53801. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  53802. __decorate([
  53803. BABYLON.serialize()
  53804. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  53805. __decorate([
  53806. BABYLON.serialize()
  53807. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  53808. __decorate([
  53809. BABYLON.serialize()
  53810. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  53811. __decorate([
  53812. BABYLON.serialize()
  53813. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  53814. __decorate([
  53815. BABYLON.serialize()
  53816. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  53817. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  53818. })(BABYLON || (BABYLON = {}));
  53819. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  53820. // BABYLON.JS Chromatic Aberration GLSL Shader
  53821. // Author: Olivier Guyot
  53822. // Separates very slightly R, G and B colors on the edges of the screen
  53823. // Inspired by Francois Tarlier & Martins Upitis
  53824. var BABYLON;
  53825. (function (BABYLON) {
  53826. var LensRenderingPipeline = (function (_super) {
  53827. __extends(LensRenderingPipeline, _super);
  53828. /**
  53829. * @constructor
  53830. *
  53831. * Effect parameters are as follow:
  53832. * {
  53833. * chromatic_aberration: number; // from 0 to x (1 for realism)
  53834. * edge_blur: number; // from 0 to x (1 for realism)
  53835. * distortion: number; // from 0 to x (1 for realism)
  53836. * grain_amount: number; // from 0 to 1
  53837. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  53838. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  53839. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  53840. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  53841. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  53842. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  53843. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  53844. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  53845. * }
  53846. * Note: if an effect parameter is unset, effect is disabled
  53847. *
  53848. * @param {string} name - The rendering pipeline name
  53849. * @param {object} parameters - An object containing all parameters (see above)
  53850. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53851. * @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)
  53852. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53853. */
  53854. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  53855. if (ratio === void 0) { ratio = 1.0; }
  53856. var _this = _super.call(this, scene.getEngine(), name) || this;
  53857. // Lens effects can be of the following:
  53858. // - chromatic aberration (slight shift of RGB colors)
  53859. // - blur on the edge of the lens
  53860. // - lens distortion
  53861. // - depth-of-field blur & highlights enhancing
  53862. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  53863. // - grain effect (noise or custom texture)
  53864. // Two additional texture samplers are needed:
  53865. // - depth map (for depth-of-field)
  53866. // - grain texture
  53867. /**
  53868. * The chromatic aberration PostProcess id in the pipeline
  53869. * @type {string}
  53870. */
  53871. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  53872. /**
  53873. * The highlights enhancing PostProcess id in the pipeline
  53874. * @type {string}
  53875. */
  53876. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  53877. /**
  53878. * The depth-of-field PostProcess id in the pipeline
  53879. * @type {string}
  53880. */
  53881. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  53882. _this._scene = scene;
  53883. // Fetch texture samplers
  53884. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  53885. if (parameters.grain_texture) {
  53886. _this._grainTexture = parameters.grain_texture;
  53887. }
  53888. else {
  53889. _this._createGrainTexture();
  53890. }
  53891. // save parameters
  53892. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  53893. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  53894. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  53895. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  53896. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  53897. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  53898. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  53899. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  53900. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  53901. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  53902. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  53903. // Create effects
  53904. _this._createChromaticAberrationPostProcess(ratio);
  53905. _this._createHighlightsPostProcess(ratio);
  53906. _this._createDepthOfFieldPostProcess(ratio / 4);
  53907. // Set up pipeline
  53908. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  53909. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  53910. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  53911. if (_this._highlightsGain === -1) {
  53912. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  53913. }
  53914. // Finish
  53915. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53916. if (cameras) {
  53917. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53918. }
  53919. return _this;
  53920. }
  53921. // public methods (self explanatory)
  53922. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  53923. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  53924. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  53925. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  53926. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  53927. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  53928. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  53929. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  53930. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  53931. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  53932. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  53933. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  53934. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  53935. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  53936. };
  53937. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  53938. this._highlightsPostProcess.updateEffect();
  53939. };
  53940. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  53941. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  53942. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  53943. this._highlightsGain = amount;
  53944. };
  53945. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  53946. if (this._highlightsGain === -1) {
  53947. this._highlightsGain = 1.0;
  53948. }
  53949. this._highlightsThreshold = amount;
  53950. };
  53951. LensRenderingPipeline.prototype.disableHighlights = function () {
  53952. this._highlightsGain = -1;
  53953. };
  53954. /**
  53955. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  53956. */
  53957. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53958. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53959. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53960. this._chromaticAberrationPostProcess = undefined;
  53961. this._highlightsPostProcess = undefined;
  53962. this._depthOfFieldPostProcess = undefined;
  53963. this._grainTexture.dispose();
  53964. if (disableDepthRender)
  53965. this._scene.disableDepthRenderer();
  53966. };
  53967. // colors shifting and distortion
  53968. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  53969. var _this = this;
  53970. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  53971. [], // samplers
  53972. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53973. this._chromaticAberrationPostProcess.onApply = function (effect) {
  53974. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  53975. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53976. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53977. };
  53978. };
  53979. // highlights enhancing
  53980. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  53981. var _this = this;
  53982. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  53983. [], // samplers
  53984. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  53985. this._highlightsPostProcess.onApply = function (effect) {
  53986. effect.setFloat('gain', _this._highlightsGain);
  53987. effect.setFloat('threshold', _this._highlightsThreshold);
  53988. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  53989. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53990. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53991. };
  53992. };
  53993. // colors shifting and distortion
  53994. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  53995. var _this = this;
  53996. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  53997. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  53998. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  53999. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54000. this._depthOfFieldPostProcess.onApply = function (effect) {
  54001. effect.setTexture("depthSampler", _this._depthTexture);
  54002. effect.setTexture("grainSampler", _this._grainTexture);
  54003. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  54004. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  54005. effect.setFloat('grain_amount', _this._grainAmount);
  54006. effect.setBool('blur_noise', _this._blurNoise);
  54007. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54008. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54009. effect.setFloat('distortion', _this._distortion);
  54010. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  54011. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  54012. effect.setFloat('aperture', _this._dofAperture);
  54013. effect.setFloat('darken', _this._dofDarken);
  54014. effect.setFloat('edge_blur', _this._edgeBlur);
  54015. effect.setBool('highlights', (_this._highlightsGain !== -1));
  54016. effect.setFloat('near', _this._scene.activeCamera.minZ);
  54017. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  54018. };
  54019. };
  54020. // creates a black and white random noise texture, 512x512
  54021. LensRenderingPipeline.prototype._createGrainTexture = function () {
  54022. var size = 512;
  54023. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54024. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54025. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54026. var context = this._grainTexture.getContext();
  54027. var rand = function (min, max) {
  54028. return Math.random() * (max - min) + min;
  54029. };
  54030. var value;
  54031. for (var x = 0; x < size; x++) {
  54032. for (var y = 0; y < size; y++) {
  54033. value = Math.floor(rand(0.42, 0.58) * 255);
  54034. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  54035. context.fillRect(x, y, 1, 1);
  54036. }
  54037. }
  54038. this._grainTexture.update(false);
  54039. };
  54040. return LensRenderingPipeline;
  54041. }(BABYLON.PostProcessRenderPipeline));
  54042. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  54043. })(BABYLON || (BABYLON = {}));
  54044. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  54045. //
  54046. // This post-process allows the modification of rendered colors by using
  54047. // a 'look-up table' (LUT). This effect is also called Color Grading.
  54048. //
  54049. // The object needs to be provided an url to a texture containing the color
  54050. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  54051. // Use an image editing software to tweak the LUT to match your needs.
  54052. //
  54053. // For an example of a color LUT, see here:
  54054. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  54055. // For explanations on color grading, see here:
  54056. // http://udn.epicgames.com/Three/ColorGrading.html
  54057. //
  54058. var BABYLON;
  54059. (function (BABYLON) {
  54060. var ColorCorrectionPostProcess = (function (_super) {
  54061. __extends(ColorCorrectionPostProcess, _super);
  54062. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  54063. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  54064. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  54065. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  54066. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54067. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54068. _this.onApply = function (effect) {
  54069. effect.setTexture("colorTable", _this._colorTableTexture);
  54070. };
  54071. return _this;
  54072. }
  54073. return ColorCorrectionPostProcess;
  54074. }(BABYLON.PostProcess));
  54075. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  54076. })(BABYLON || (BABYLON = {}));
  54077. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  54078. /// <reference path="babylon.freeCamera.ts" />
  54079. /// <reference path="babylon.arcRotateCamera.ts" />
  54080. /// <reference path="babylon.gamepadCamera.ts" />
  54081. /// <reference path="babylon.universalCamera.ts" />
  54082. var BABYLON;
  54083. (function (BABYLON) {
  54084. var AnaglyphFreeCamera = (function (_super) {
  54085. __extends(AnaglyphFreeCamera, _super);
  54086. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  54087. var _this = _super.call(this, name, position, scene) || this;
  54088. _this.interaxialDistance = interaxialDistance;
  54089. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54090. return _this;
  54091. }
  54092. AnaglyphFreeCamera.prototype.getClassName = function () {
  54093. return "AnaglyphFreeCamera";
  54094. };
  54095. return AnaglyphFreeCamera;
  54096. }(BABYLON.FreeCamera));
  54097. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  54098. var AnaglyphArcRotateCamera = (function (_super) {
  54099. __extends(AnaglyphArcRotateCamera, _super);
  54100. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  54101. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  54102. _this.interaxialDistance = interaxialDistance;
  54103. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54104. return _this;
  54105. }
  54106. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  54107. return "AnaglyphArcRotateCamera";
  54108. };
  54109. return AnaglyphArcRotateCamera;
  54110. }(BABYLON.ArcRotateCamera));
  54111. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  54112. var AnaglyphGamepadCamera = (function (_super) {
  54113. __extends(AnaglyphGamepadCamera, _super);
  54114. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  54115. var _this = _super.call(this, name, position, scene) || this;
  54116. _this.interaxialDistance = interaxialDistance;
  54117. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54118. return _this;
  54119. }
  54120. AnaglyphGamepadCamera.prototype.getClassName = function () {
  54121. return "AnaglyphGamepadCamera";
  54122. };
  54123. return AnaglyphGamepadCamera;
  54124. }(BABYLON.GamepadCamera));
  54125. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  54126. var AnaglyphUniversalCamera = (function (_super) {
  54127. __extends(AnaglyphUniversalCamera, _super);
  54128. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  54129. var _this = _super.call(this, name, position, scene) || this;
  54130. _this.interaxialDistance = interaxialDistance;
  54131. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54132. return _this;
  54133. }
  54134. AnaglyphUniversalCamera.prototype.getClassName = function () {
  54135. return "AnaglyphUniversalCamera";
  54136. };
  54137. return AnaglyphUniversalCamera;
  54138. }(BABYLON.UniversalCamera));
  54139. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  54140. var StereoscopicFreeCamera = (function (_super) {
  54141. __extends(StereoscopicFreeCamera, _super);
  54142. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54143. var _this = _super.call(this, name, position, scene) || this;
  54144. _this.interaxialDistance = interaxialDistance;
  54145. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54146. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54147. return _this;
  54148. }
  54149. StereoscopicFreeCamera.prototype.getClassName = function () {
  54150. return "StereoscopicFreeCamera";
  54151. };
  54152. return StereoscopicFreeCamera;
  54153. }(BABYLON.FreeCamera));
  54154. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  54155. var StereoscopicArcRotateCamera = (function (_super) {
  54156. __extends(StereoscopicArcRotateCamera, _super);
  54157. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  54158. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  54159. _this.interaxialDistance = interaxialDistance;
  54160. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54161. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54162. return _this;
  54163. }
  54164. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  54165. return "StereoscopicArcRotateCamera";
  54166. };
  54167. return StereoscopicArcRotateCamera;
  54168. }(BABYLON.ArcRotateCamera));
  54169. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  54170. var StereoscopicGamepadCamera = (function (_super) {
  54171. __extends(StereoscopicGamepadCamera, _super);
  54172. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54173. var _this = _super.call(this, name, position, scene) || this;
  54174. _this.interaxialDistance = interaxialDistance;
  54175. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54176. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54177. return _this;
  54178. }
  54179. StereoscopicGamepadCamera.prototype.getClassName = function () {
  54180. return "StereoscopicGamepadCamera";
  54181. };
  54182. return StereoscopicGamepadCamera;
  54183. }(BABYLON.GamepadCamera));
  54184. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  54185. var StereoscopicUniversalCamera = (function (_super) {
  54186. __extends(StereoscopicUniversalCamera, _super);
  54187. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54188. var _this = _super.call(this, name, position, scene) || this;
  54189. _this.interaxialDistance = interaxialDistance;
  54190. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54191. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54192. return _this;
  54193. }
  54194. StereoscopicUniversalCamera.prototype.getClassName = function () {
  54195. return "StereoscopicUniversalCamera";
  54196. };
  54197. return StereoscopicUniversalCamera;
  54198. }(BABYLON.UniversalCamera));
  54199. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  54200. })(BABYLON || (BABYLON = {}));
  54201. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  54202. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  54203. var BABYLON;
  54204. (function (BABYLON) {
  54205. var HDRRenderingPipeline = (function (_super) {
  54206. __extends(HDRRenderingPipeline, _super);
  54207. /**
  54208. * @constructor
  54209. * @param {string} name - The rendering pipeline name
  54210. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54211. * @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)
  54212. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54213. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54214. */
  54215. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54216. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54217. var _this = _super.call(this, scene.getEngine(), name) || this;
  54218. /**
  54219. * Public members
  54220. */
  54221. // Gaussian Blur
  54222. /**
  54223. * Gaussian blur coefficient
  54224. * @type {number}
  54225. */
  54226. _this.gaussCoeff = 0.3;
  54227. /**
  54228. * Gaussian blur mean
  54229. * @type {number}
  54230. */
  54231. _this.gaussMean = 1.0;
  54232. /**
  54233. * Gaussian blur standard deviation
  54234. * @type {number}
  54235. */
  54236. _this.gaussStandDev = 0.8;
  54237. /**
  54238. * Gaussian blur multiplier. Multiplies the blur effect
  54239. * @type {number}
  54240. */
  54241. _this.gaussMultiplier = 4.0;
  54242. // HDR
  54243. /**
  54244. * Exposure, controls the overall intensity of the pipeline
  54245. * @type {number}
  54246. */
  54247. _this.exposure = 1.0;
  54248. /**
  54249. * Minimum luminance that the post-process can output. Luminance is >= 0
  54250. * @type {number}
  54251. */
  54252. _this.minimumLuminance = 1.0;
  54253. /**
  54254. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  54255. * @type {number}
  54256. */
  54257. _this.maximumLuminance = 1e20;
  54258. /**
  54259. * Increase rate for luminance: eye adaptation speed to dark
  54260. * @type {number}
  54261. */
  54262. _this.luminanceIncreaserate = 0.5;
  54263. /**
  54264. * Decrease rate for luminance: eye adaptation speed to bright
  54265. * @type {number}
  54266. */
  54267. _this.luminanceDecreaseRate = 0.5;
  54268. // Bright pass
  54269. /**
  54270. * Minimum luminance needed to compute HDR
  54271. * @type {number}
  54272. */
  54273. _this.brightThreshold = 0.8;
  54274. _this._needUpdate = true;
  54275. _this._scene = scene;
  54276. // Bright pass
  54277. _this._createBrightPassPostProcess(scene, ratio);
  54278. // Down sample X4
  54279. _this._createDownSampleX4PostProcess(scene, ratio);
  54280. // Create gaussian blur post-processes
  54281. _this._createGaussianBlurPostProcess(scene, ratio);
  54282. // Texture adder
  54283. _this._createTextureAdderPostProcess(scene, ratio);
  54284. // Luminance generator
  54285. _this._createLuminanceGeneratorPostProcess(scene);
  54286. // HDR
  54287. _this._createHDRPostProcess(scene, ratio);
  54288. // Pass postprocess
  54289. if (originalPostProcess === null) {
  54290. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  54291. }
  54292. else {
  54293. _this._originalPostProcess = originalPostProcess;
  54294. }
  54295. // Configure pipeline
  54296. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  54297. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  54298. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  54299. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  54300. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  54301. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  54302. var addDownSamplerPostProcess = function (id) {
  54303. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  54304. };
  54305. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  54306. addDownSamplerPostProcess(i);
  54307. }
  54308. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  54309. // Finish
  54310. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54311. if (cameras !== null) {
  54312. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54313. }
  54314. _this.update();
  54315. return _this;
  54316. }
  54317. /**
  54318. * Tells the pipeline to update its post-processes
  54319. */
  54320. HDRRenderingPipeline.prototype.update = function () {
  54321. this._needUpdate = true;
  54322. };
  54323. /**
  54324. * Returns the current calculated luminance
  54325. */
  54326. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  54327. return this._hdrCurrentLuminance;
  54328. };
  54329. /**
  54330. * Returns the currently drawn luminance
  54331. */
  54332. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  54333. return this._hdrOutputLuminance;
  54334. };
  54335. /**
  54336. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  54337. */
  54338. HDRRenderingPipeline.prototype.dispose = function () {
  54339. for (var i = 0; i < this._scene.cameras.length; i++) {
  54340. var camera = this._scene.cameras[i];
  54341. this._originalPostProcess.dispose(camera);
  54342. this._brightPassPostProcess.dispose(camera);
  54343. this._downSampleX4PostProcess.dispose(camera);
  54344. this._guassianBlurHPostProcess.dispose(camera);
  54345. this._guassianBlurVPostProcess.dispose(camera);
  54346. this._textureAdderPostProcess.dispose(camera);
  54347. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  54348. this._downSamplePostProcesses[j].dispose(camera);
  54349. }
  54350. this._hdrPostProcess.dispose(camera);
  54351. }
  54352. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54353. _super.prototype.dispose.call(this);
  54354. };
  54355. /**
  54356. * Creates the HDR post-process and computes the luminance adaptation
  54357. */
  54358. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  54359. var _this = this;
  54360. var hdrLastLuminance = 0.0;
  54361. this._hdrOutputLuminance = -1.0;
  54362. this._hdrCurrentLuminance = 1.0;
  54363. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  54364. this._hdrPostProcess.onApply = function (effect) {
  54365. if (_this._hdrOutputLuminance < 0.0) {
  54366. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  54367. }
  54368. else {
  54369. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  54370. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  54371. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  54372. }
  54373. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  54374. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  54375. }
  54376. else {
  54377. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  54378. }
  54379. }
  54380. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  54381. hdrLastLuminance += scene.getEngine().getDeltaTime();
  54382. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  54383. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  54384. effect.setFloat("exposure", _this.exposure);
  54385. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  54386. _this._needUpdate = false;
  54387. };
  54388. };
  54389. /**
  54390. * Texture Adder post-process
  54391. */
  54392. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54393. var _this = this;
  54394. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  54395. this._textureAdderPostProcess.onApply = function (effect) {
  54396. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  54397. };
  54398. };
  54399. /**
  54400. * Down sample X4 post-process
  54401. */
  54402. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54403. var _this = this;
  54404. var downSampleX4Offsets = new Array(32);
  54405. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  54406. this._downSampleX4PostProcess.onApply = function (effect) {
  54407. if (_this._needUpdate) {
  54408. var id = 0;
  54409. for (var i = -2; i < 2; i++) {
  54410. for (var j = -2; j < 2; j++) {
  54411. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  54412. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  54413. id += 2;
  54414. }
  54415. }
  54416. }
  54417. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54418. };
  54419. };
  54420. /**
  54421. * Bright pass post-process
  54422. */
  54423. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54424. var _this = this;
  54425. var brightOffsets = new Array(8);
  54426. var brightPassCallback = function (effect) {
  54427. if (_this._needUpdate) {
  54428. var sU = (1.0 / _this._brightPassPostProcess.width);
  54429. var sV = (1.0 / _this._brightPassPostProcess.height);
  54430. brightOffsets[0] = -0.5 * sU;
  54431. brightOffsets[1] = 0.5 * sV;
  54432. brightOffsets[2] = 0.5 * sU;
  54433. brightOffsets[3] = 0.5 * sV;
  54434. brightOffsets[4] = -0.5 * sU;
  54435. brightOffsets[5] = -0.5 * sV;
  54436. brightOffsets[6] = 0.5 * sU;
  54437. brightOffsets[7] = -0.5 * sV;
  54438. }
  54439. effect.setArray2("dsOffsets", brightOffsets);
  54440. effect.setFloat("brightThreshold", _this.brightThreshold);
  54441. };
  54442. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  54443. this._brightPassPostProcess.onApply = brightPassCallback;
  54444. };
  54445. /**
  54446. * Luminance generator. Creates the luminance post-process and down sample post-processes
  54447. */
  54448. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  54449. var _this = this;
  54450. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  54451. var luminanceOffsets = new Array(8);
  54452. var downSampleOffsets = new Array(18);
  54453. var halfDestPixelSize;
  54454. this._downSamplePostProcesses = new Array(lumSteps);
  54455. // Utils for luminance
  54456. var luminanceUpdateSourceOffsets = function (width, height) {
  54457. var sU = (1.0 / width);
  54458. var sV = (1.0 / height);
  54459. luminanceOffsets[0] = -0.5 * sU;
  54460. luminanceOffsets[1] = 0.5 * sV;
  54461. luminanceOffsets[2] = 0.5 * sU;
  54462. luminanceOffsets[3] = 0.5 * sV;
  54463. luminanceOffsets[4] = -0.5 * sU;
  54464. luminanceOffsets[5] = -0.5 * sV;
  54465. luminanceOffsets[6] = 0.5 * sU;
  54466. luminanceOffsets[7] = -0.5 * sV;
  54467. };
  54468. var luminanceUpdateDestOffsets = function (width, height) {
  54469. var id = 0;
  54470. for (var x = -1; x < 2; x++) {
  54471. for (var y = -1; y < 2; y++) {
  54472. downSampleOffsets[id] = (x) / width;
  54473. downSampleOffsets[id + 1] = (y) / height;
  54474. id += 2;
  54475. }
  54476. }
  54477. };
  54478. // Luminance callback
  54479. var luminanceCallback = function (effect) {
  54480. if (_this._needUpdate) {
  54481. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  54482. }
  54483. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  54484. effect.setArray2("lumOffsets", luminanceOffsets);
  54485. };
  54486. // Down sample callbacks
  54487. var downSampleCallback = function (indice) {
  54488. var i = indice;
  54489. return function (effect) {
  54490. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  54491. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  54492. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  54493. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  54494. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  54495. effect.setArray2("dsOffsets", downSampleOffsets);
  54496. };
  54497. };
  54498. var downSampleAfterRenderCallback = function (effect) {
  54499. // Unpack result
  54500. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  54501. 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);
  54502. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  54503. };
  54504. // Create luminance post-process
  54505. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  54506. 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);
  54507. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  54508. // Create down sample post-processes
  54509. for (var i = lumSteps - 2; i >= 0; i--) {
  54510. var length = Math.pow(3, i);
  54511. ratio = { width: length, height: length };
  54512. var defines = "#define DOWN_SAMPLE\n";
  54513. if (i === 0) {
  54514. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  54515. }
  54516. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  54517. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  54518. if (i === 0) {
  54519. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  54520. }
  54521. }
  54522. };
  54523. /**
  54524. * Gaussian blur post-processes. Horizontal and Vertical
  54525. */
  54526. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  54527. var _this = this;
  54528. var blurOffsetsW = new Array(9);
  54529. var blurOffsetsH = new Array(9);
  54530. var blurWeights = new Array(9);
  54531. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  54532. // Utils for gaussian blur
  54533. var calculateBlurOffsets = function (height) {
  54534. var lastOutputDimensions = {
  54535. width: scene.getEngine().getRenderWidth(),
  54536. height: scene.getEngine().getRenderHeight()
  54537. };
  54538. for (var i = 0; i < 9; i++) {
  54539. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  54540. if (height) {
  54541. blurOffsetsH[i] = value;
  54542. }
  54543. else {
  54544. blurOffsetsW[i] = value;
  54545. }
  54546. }
  54547. };
  54548. var calculateWeights = function () {
  54549. var x = 0.0;
  54550. for (var i = 0; i < 9; i++) {
  54551. x = (i - 4.0) / 4.0;
  54552. 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));
  54553. }
  54554. };
  54555. // Callback
  54556. var gaussianBlurCallback = function (height) {
  54557. return function (effect) {
  54558. if (_this._needUpdate) {
  54559. calculateWeights();
  54560. calculateBlurOffsets(height);
  54561. }
  54562. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  54563. effect.setArray("blurWeights", blurWeights);
  54564. effect.setFloat("multiplier", _this.gaussMultiplier);
  54565. };
  54566. };
  54567. // Create horizontal gaussian blur post-processes
  54568. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  54569. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  54570. // Create vertical gaussian blur post-process
  54571. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  54572. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  54573. };
  54574. return HDRRenderingPipeline;
  54575. }(BABYLON.PostProcessRenderPipeline));
  54576. // Luminance generator
  54577. HDRRenderingPipeline.LUM_STEPS = 6;
  54578. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  54579. })(BABYLON || (BABYLON = {}));
  54580. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  54581. var BABYLON;
  54582. (function (BABYLON) {
  54583. var FaceAdjacencies = (function () {
  54584. function FaceAdjacencies() {
  54585. this.edges = new Array();
  54586. this.edgesConnectedCount = 0;
  54587. }
  54588. return FaceAdjacencies;
  54589. }());
  54590. var EdgesRenderer = (function () {
  54591. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  54592. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  54593. if (epsilon === void 0) { epsilon = 0.95; }
  54594. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  54595. this.edgesWidthScalerForOrthographic = 1000.0;
  54596. this.edgesWidthScalerForPerspective = 50.0;
  54597. this._linesPositions = new Array();
  54598. this._linesNormals = new Array();
  54599. this._linesIndices = new Array();
  54600. this._buffers = {};
  54601. this._checkVerticesInsteadOfIndices = false;
  54602. this._source = source;
  54603. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  54604. this._epsilon = epsilon;
  54605. this._prepareRessources();
  54606. this._generateEdgesLines();
  54607. }
  54608. EdgesRenderer.prototype._prepareRessources = function () {
  54609. if (this._lineShader) {
  54610. return;
  54611. }
  54612. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  54613. attributes: ["position", "normal"],
  54614. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  54615. });
  54616. this._lineShader.disableDepthWrite = true;
  54617. this._lineShader.backFaceCulling = false;
  54618. };
  54619. EdgesRenderer.prototype.dispose = function () {
  54620. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  54621. if (buffer) {
  54622. buffer.dispose();
  54623. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  54624. }
  54625. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  54626. if (buffer) {
  54627. buffer.dispose();
  54628. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  54629. }
  54630. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  54631. this._lineShader.dispose();
  54632. };
  54633. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  54634. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  54635. return 0;
  54636. }
  54637. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  54638. return 1;
  54639. }
  54640. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  54641. return 2;
  54642. }
  54643. return -1;
  54644. };
  54645. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  54646. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  54647. return 0;
  54648. }
  54649. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  54650. return 1;
  54651. }
  54652. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  54653. return 2;
  54654. }
  54655. return -1;
  54656. };
  54657. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  54658. var needToCreateLine;
  54659. if (edge === undefined) {
  54660. needToCreateLine = true;
  54661. }
  54662. else {
  54663. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  54664. needToCreateLine = dotProduct < this._epsilon;
  54665. }
  54666. if (needToCreateLine) {
  54667. var offset = this._linesPositions.length / 3;
  54668. var normal = p0.subtract(p1);
  54669. normal.normalize();
  54670. // Positions
  54671. this._linesPositions.push(p0.x);
  54672. this._linesPositions.push(p0.y);
  54673. this._linesPositions.push(p0.z);
  54674. this._linesPositions.push(p0.x);
  54675. this._linesPositions.push(p0.y);
  54676. this._linesPositions.push(p0.z);
  54677. this._linesPositions.push(p1.x);
  54678. this._linesPositions.push(p1.y);
  54679. this._linesPositions.push(p1.z);
  54680. this._linesPositions.push(p1.x);
  54681. this._linesPositions.push(p1.y);
  54682. this._linesPositions.push(p1.z);
  54683. // Normals
  54684. this._linesNormals.push(p1.x);
  54685. this._linesNormals.push(p1.y);
  54686. this._linesNormals.push(p1.z);
  54687. this._linesNormals.push(-1);
  54688. this._linesNormals.push(p1.x);
  54689. this._linesNormals.push(p1.y);
  54690. this._linesNormals.push(p1.z);
  54691. this._linesNormals.push(1);
  54692. this._linesNormals.push(p0.x);
  54693. this._linesNormals.push(p0.y);
  54694. this._linesNormals.push(p0.z);
  54695. this._linesNormals.push(-1);
  54696. this._linesNormals.push(p0.x);
  54697. this._linesNormals.push(p0.y);
  54698. this._linesNormals.push(p0.z);
  54699. this._linesNormals.push(1);
  54700. // Indices
  54701. this._linesIndices.push(offset);
  54702. this._linesIndices.push(offset + 1);
  54703. this._linesIndices.push(offset + 2);
  54704. this._linesIndices.push(offset);
  54705. this._linesIndices.push(offset + 2);
  54706. this._linesIndices.push(offset + 3);
  54707. }
  54708. };
  54709. EdgesRenderer.prototype._generateEdgesLines = function () {
  54710. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54711. var indices = this._source.getIndices();
  54712. // First let's find adjacencies
  54713. var adjacencies = new Array();
  54714. var faceNormals = new Array();
  54715. var index;
  54716. var faceAdjacencies;
  54717. // Prepare faces
  54718. for (index = 0; index < indices.length; index += 3) {
  54719. faceAdjacencies = new FaceAdjacencies();
  54720. var p0Index = indices[index];
  54721. var p1Index = indices[index + 1];
  54722. var p2Index = indices[index + 2];
  54723. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  54724. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  54725. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  54726. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  54727. faceNormal.normalize();
  54728. faceNormals.push(faceNormal);
  54729. adjacencies.push(faceAdjacencies);
  54730. }
  54731. // Scan
  54732. for (index = 0; index < adjacencies.length; index++) {
  54733. faceAdjacencies = adjacencies[index];
  54734. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  54735. var otherFaceAdjacencies = adjacencies[otherIndex];
  54736. if (faceAdjacencies.edgesConnectedCount === 3) {
  54737. break;
  54738. }
  54739. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  54740. continue;
  54741. }
  54742. var otherP0 = indices[otherIndex * 3];
  54743. var otherP1 = indices[otherIndex * 3 + 1];
  54744. var otherP2 = indices[otherIndex * 3 + 2];
  54745. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  54746. var otherEdgeIndex;
  54747. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  54748. continue;
  54749. }
  54750. switch (edgeIndex) {
  54751. case 0:
  54752. if (this._checkVerticesInsteadOfIndices) {
  54753. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  54754. }
  54755. else {
  54756. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  54757. }
  54758. break;
  54759. case 1:
  54760. if (this._checkVerticesInsteadOfIndices) {
  54761. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  54762. }
  54763. else {
  54764. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  54765. }
  54766. break;
  54767. case 2:
  54768. if (this._checkVerticesInsteadOfIndices) {
  54769. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  54770. }
  54771. else {
  54772. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  54773. }
  54774. break;
  54775. }
  54776. if (otherEdgeIndex === -1) {
  54777. continue;
  54778. }
  54779. faceAdjacencies.edges[edgeIndex] = otherIndex;
  54780. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  54781. faceAdjacencies.edgesConnectedCount++;
  54782. otherFaceAdjacencies.edgesConnectedCount++;
  54783. if (faceAdjacencies.edgesConnectedCount === 3) {
  54784. break;
  54785. }
  54786. }
  54787. }
  54788. }
  54789. // Create lines
  54790. for (index = 0; index < adjacencies.length; index++) {
  54791. // 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
  54792. var current = adjacencies[index];
  54793. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  54794. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  54795. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  54796. }
  54797. // Merge into a single mesh
  54798. var engine = this._source.getScene().getEngine();
  54799. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  54800. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  54801. this._ib = engine.createIndexBuffer(this._linesIndices);
  54802. this._indicesCount = this._linesIndices.length;
  54803. };
  54804. EdgesRenderer.prototype.render = function () {
  54805. if (!this._lineShader.isReady()) {
  54806. return;
  54807. }
  54808. var scene = this._source.getScene();
  54809. var engine = scene.getEngine();
  54810. this._lineShader._preBind();
  54811. // VBOs
  54812. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  54813. scene.resetCachedMaterial();
  54814. this._lineShader.setColor4("color", this._source.edgesColor);
  54815. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  54816. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  54817. }
  54818. else {
  54819. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  54820. }
  54821. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  54822. this._lineShader.bind(this._source.getWorldMatrix());
  54823. // Draw order
  54824. engine.draw(true, 0, this._indicesCount);
  54825. this._lineShader.unbind();
  54826. engine.setDepthWrite(true);
  54827. };
  54828. return EdgesRenderer;
  54829. }());
  54830. BABYLON.EdgesRenderer = EdgesRenderer;
  54831. })(BABYLON || (BABYLON = {}));
  54832. //# sourceMappingURL=babylon.edgesRenderer.js.map
  54833. var BABYLON;
  54834. (function (BABYLON) {
  54835. var TonemappingOperator;
  54836. (function (TonemappingOperator) {
  54837. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  54838. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  54839. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  54840. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  54841. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  54842. ;
  54843. var TonemapPostProcess = (function (_super) {
  54844. __extends(TonemapPostProcess, _super);
  54845. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  54846. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54847. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54848. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  54849. _this._operator = _operator;
  54850. _this.exposureAdjustment = exposureAdjustment;
  54851. var defines = "#define ";
  54852. if (_this._operator === TonemappingOperator.Hable)
  54853. defines += "HABLE_TONEMAPPING";
  54854. else if (_this._operator === TonemappingOperator.Reinhard)
  54855. defines += "REINHARD_TONEMAPPING";
  54856. else if (_this._operator === TonemappingOperator.HejiDawson)
  54857. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  54858. else if (_this._operator === TonemappingOperator.Photographic)
  54859. defines += "PHOTOGRAPHIC_TONEMAPPING";
  54860. //sadly a second call to create the effect.
  54861. _this.updateEffect(defines);
  54862. _this.onApply = function (effect) {
  54863. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  54864. };
  54865. return _this;
  54866. }
  54867. return TonemapPostProcess;
  54868. }(BABYLON.PostProcess));
  54869. BABYLON.TonemapPostProcess = TonemapPostProcess;
  54870. })(BABYLON || (BABYLON = {}));
  54871. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  54872. var BABYLON;
  54873. (function (BABYLON) {
  54874. var ReflectionProbe = (function () {
  54875. function ReflectionProbe(name, size, scene, generateMipMaps) {
  54876. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54877. var _this = this;
  54878. this.name = name;
  54879. this._viewMatrix = BABYLON.Matrix.Identity();
  54880. this._target = BABYLON.Vector3.Zero();
  54881. this._add = BABYLON.Vector3.Zero();
  54882. this.invertYAxis = false;
  54883. this.position = BABYLON.Vector3.Zero();
  54884. this._scene = scene;
  54885. this._scene.reflectionProbes.push(this);
  54886. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  54887. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  54888. switch (faceIndex) {
  54889. case 0:
  54890. _this._add.copyFromFloats(1, 0, 0);
  54891. break;
  54892. case 1:
  54893. _this._add.copyFromFloats(-1, 0, 0);
  54894. break;
  54895. case 2:
  54896. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  54897. break;
  54898. case 3:
  54899. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  54900. break;
  54901. case 4:
  54902. _this._add.copyFromFloats(0, 0, 1);
  54903. break;
  54904. case 5:
  54905. _this._add.copyFromFloats(0, 0, -1);
  54906. break;
  54907. }
  54908. if (_this._attachedMesh) {
  54909. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  54910. }
  54911. _this.position.addToRef(_this._add, _this._target);
  54912. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  54913. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  54914. });
  54915. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  54916. scene.updateTransformMatrix(true);
  54917. });
  54918. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  54919. }
  54920. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  54921. get: function () {
  54922. return this._renderTargetTexture.samples;
  54923. },
  54924. set: function (value) {
  54925. this._renderTargetTexture.samples = value;
  54926. },
  54927. enumerable: true,
  54928. configurable: true
  54929. });
  54930. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  54931. get: function () {
  54932. return this._renderTargetTexture.refreshRate;
  54933. },
  54934. set: function (value) {
  54935. this._renderTargetTexture.refreshRate = value;
  54936. },
  54937. enumerable: true,
  54938. configurable: true
  54939. });
  54940. ReflectionProbe.prototype.getScene = function () {
  54941. return this._scene;
  54942. };
  54943. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  54944. get: function () {
  54945. return this._renderTargetTexture;
  54946. },
  54947. enumerable: true,
  54948. configurable: true
  54949. });
  54950. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  54951. get: function () {
  54952. return this._renderTargetTexture.renderList;
  54953. },
  54954. enumerable: true,
  54955. configurable: true
  54956. });
  54957. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  54958. this._attachedMesh = mesh;
  54959. };
  54960. ReflectionProbe.prototype.dispose = function () {
  54961. var index = this._scene.reflectionProbes.indexOf(this);
  54962. if (index !== -1) {
  54963. // Remove from the scene if found
  54964. this._scene.reflectionProbes.splice(index, 1);
  54965. }
  54966. if (this._renderTargetTexture) {
  54967. this._renderTargetTexture.dispose();
  54968. this._renderTargetTexture = null;
  54969. }
  54970. };
  54971. return ReflectionProbe;
  54972. }());
  54973. BABYLON.ReflectionProbe = ReflectionProbe;
  54974. })(BABYLON || (BABYLON = {}));
  54975. //# sourceMappingURL=babylon.reflectionProbe.js.map
  54976. var BABYLON;
  54977. (function (BABYLON) {
  54978. var SolidParticle = (function () {
  54979. /**
  54980. * Creates a Solid Particle object.
  54981. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  54982. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  54983. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  54984. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  54985. * `shapeId` (integer) is the model shape identifier in the SPS.
  54986. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  54987. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  54988. */
  54989. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  54990. this.idx = 0; // particle global index
  54991. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  54992. this.position = BABYLON.Vector3.Zero(); // position
  54993. this.rotation = BABYLON.Vector3.Zero(); // rotation
  54994. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  54995. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  54996. this.velocity = BABYLON.Vector3.Zero(); // velocity
  54997. this.alive = true; // alive
  54998. this.isVisible = true; // visibility
  54999. this._pos = 0; // index of this particle in the global "positions" array
  55000. this.shapeId = 0; // model shape id
  55001. this.idxInShape = 0; // index of the particle in its shape id
  55002. this.idx = particleIndex;
  55003. this._pos = positionIndex;
  55004. this._model = model;
  55005. this.shapeId = shapeId;
  55006. this.idxInShape = idxInShape;
  55007. this._sps = sps;
  55008. if (modelBoundingInfo) {
  55009. this._modelBoundingInfo = modelBoundingInfo;
  55010. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  55011. }
  55012. }
  55013. Object.defineProperty(SolidParticle.prototype, "scale", {
  55014. /**
  55015. * legacy support, changed scale to scaling
  55016. */
  55017. get: function () {
  55018. return this.scaling;
  55019. },
  55020. set: function (scale) {
  55021. this.scaling = scale;
  55022. },
  55023. enumerable: true,
  55024. configurable: true
  55025. });
  55026. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  55027. /**
  55028. * legacy support, changed quaternion to rotationQuaternion
  55029. */
  55030. get: function () {
  55031. return this.rotationQuaternion;
  55032. },
  55033. set: function (q) {
  55034. this.rotationQuaternion = q;
  55035. },
  55036. enumerable: true,
  55037. configurable: true
  55038. });
  55039. /**
  55040. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  55041. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  55042. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  55043. */
  55044. SolidParticle.prototype.intersectsMesh = function (target) {
  55045. if (!this._boundingInfo || !target._boundingInfo) {
  55046. return false;
  55047. }
  55048. if (this._sps._bSphereOnly) {
  55049. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  55050. }
  55051. return this._boundingInfo.intersects(target._boundingInfo, false);
  55052. };
  55053. return SolidParticle;
  55054. }());
  55055. BABYLON.SolidParticle = SolidParticle;
  55056. var ModelShape = (function () {
  55057. /**
  55058. * 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.
  55059. * SPS internal tool, don't use it manually.
  55060. */
  55061. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  55062. this.shapeID = id;
  55063. this._shape = shape;
  55064. this._shapeUV = shapeUV;
  55065. this._positionFunction = posFunction;
  55066. this._vertexFunction = vtxFunction;
  55067. }
  55068. return ModelShape;
  55069. }());
  55070. BABYLON.ModelShape = ModelShape;
  55071. })(BABYLON || (BABYLON = {}));
  55072. //# sourceMappingURL=babylon.solidParticle.js.map
  55073. var BABYLON;
  55074. (function (BABYLON) {
  55075. /**
  55076. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  55077. */
  55078. var SolidParticleSystem = (function () {
  55079. /**
  55080. * Creates a SPS (Solid Particle System) object.
  55081. * `name` (String) is the SPS name, this will be the underlying mesh name.
  55082. * `scene` (Scene) is the scene in which the SPS is added.
  55083. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  55084. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  55085. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  55086. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  55087. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  55088. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  55089. */
  55090. function SolidParticleSystem(name, scene, options) {
  55091. // public members
  55092. /**
  55093. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  55094. * Example : var p = SPS.particles[i];
  55095. */
  55096. this.particles = new Array();
  55097. /**
  55098. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  55099. */
  55100. this.nbParticles = 0;
  55101. /**
  55102. * If the particles must ever face the camera (default false). Useful for planar particles.
  55103. */
  55104. this.billboard = false;
  55105. /**
  55106. * Recompute normals when adding a shape
  55107. */
  55108. this.recomputeNormals = true;
  55109. /**
  55110. * This a counter ofr your own usage. It's not set by any SPS functions.
  55111. */
  55112. this.counter = 0;
  55113. /**
  55114. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  55115. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  55116. */
  55117. this.vars = {};
  55118. this._positions = new Array();
  55119. this._indices = new Array();
  55120. this._normals = new Array();
  55121. this._colors = new Array();
  55122. this._uvs = new Array();
  55123. this._index = 0; // indices index
  55124. this._updatable = true;
  55125. this._pickable = false;
  55126. this._isVisibilityBoxLocked = false;
  55127. this._alwaysVisible = false;
  55128. this._shapeCounter = 0;
  55129. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  55130. this._color = new BABYLON.Color4(0, 0, 0, 0);
  55131. this._computeParticleColor = true;
  55132. this._computeParticleTexture = true;
  55133. this._computeParticleRotation = true;
  55134. this._computeParticleVertex = false;
  55135. this._computeBoundingBox = false;
  55136. this._cam_axisZ = BABYLON.Vector3.Zero();
  55137. this._cam_axisY = BABYLON.Vector3.Zero();
  55138. this._cam_axisX = BABYLON.Vector3.Zero();
  55139. this._axisX = BABYLON.Axis.X;
  55140. this._axisY = BABYLON.Axis.Y;
  55141. this._axisZ = BABYLON.Axis.Z;
  55142. this._camDir = BABYLON.Vector3.Zero();
  55143. this._rotMatrix = new BABYLON.Matrix();
  55144. this._invertMatrix = new BABYLON.Matrix();
  55145. this._rotated = BABYLON.Vector3.Zero();
  55146. this._quaternion = new BABYLON.Quaternion();
  55147. this._vertex = BABYLON.Vector3.Zero();
  55148. this._normal = BABYLON.Vector3.Zero();
  55149. this._yaw = 0.0;
  55150. this._pitch = 0.0;
  55151. this._roll = 0.0;
  55152. this._halfroll = 0.0;
  55153. this._halfpitch = 0.0;
  55154. this._halfyaw = 0.0;
  55155. this._sinRoll = 0.0;
  55156. this._cosRoll = 0.0;
  55157. this._sinPitch = 0.0;
  55158. this._cosPitch = 0.0;
  55159. this._sinYaw = 0.0;
  55160. this._cosYaw = 0.0;
  55161. this._w = 0.0;
  55162. this._mustUnrotateFixedNormals = false;
  55163. this._minimum = BABYLON.Tmp.Vector3[0];
  55164. this._maximum = BABYLON.Tmp.Vector3[1];
  55165. this._scale = BABYLON.Tmp.Vector3[2];
  55166. this._translation = BABYLON.Tmp.Vector3[3];
  55167. this._minBbox = BABYLON.Tmp.Vector3[4];
  55168. this._maxBbox = BABYLON.Tmp.Vector3[5];
  55169. this._particlesIntersect = false;
  55170. this._bSphereOnly = false;
  55171. this._bSphereRadiusFactor = 1.0;
  55172. this.name = name;
  55173. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55174. this._camera = scene.activeCamera;
  55175. this._pickable = options ? options.isPickable : false;
  55176. this._particlesIntersect = options ? options.particleIntersection : false;
  55177. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  55178. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  55179. if (options && options.updatable) {
  55180. this._updatable = options.updatable;
  55181. }
  55182. else {
  55183. this._updatable = true;
  55184. }
  55185. if (this._pickable) {
  55186. this.pickedParticles = [];
  55187. }
  55188. }
  55189. /**
  55190. * Builds the SPS underlying mesh. Returns a standard Mesh.
  55191. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  55192. */
  55193. SolidParticleSystem.prototype.buildMesh = function () {
  55194. if (this.nbParticles === 0) {
  55195. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  55196. this.addShape(triangle, 1);
  55197. triangle.dispose();
  55198. }
  55199. this._positions32 = new Float32Array(this._positions);
  55200. this._uvs32 = new Float32Array(this._uvs);
  55201. this._colors32 = new Float32Array(this._colors);
  55202. if (this.recomputeNormals) {
  55203. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  55204. }
  55205. this._normals32 = new Float32Array(this._normals);
  55206. this._fixedNormal32 = new Float32Array(this._normals);
  55207. if (this._mustUnrotateFixedNormals) {
  55208. this._unrotateFixedNormals();
  55209. }
  55210. var vertexData = new BABYLON.VertexData();
  55211. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  55212. vertexData.indices = this._indices;
  55213. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  55214. if (this._uvs32) {
  55215. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  55216. ;
  55217. }
  55218. if (this._colors32) {
  55219. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  55220. }
  55221. var mesh = new BABYLON.Mesh(this.name, this._scene);
  55222. vertexData.applyToMesh(mesh, this._updatable);
  55223. this.mesh = mesh;
  55224. this.mesh.isPickable = this._pickable;
  55225. // free memory
  55226. this._positions = null;
  55227. this._normals = null;
  55228. this._uvs = null;
  55229. this._colors = null;
  55230. if (!this._updatable) {
  55231. this.particles.length = 0;
  55232. }
  55233. return mesh;
  55234. };
  55235. /**
  55236. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  55237. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  55238. * Thus the particles generated from `digest()` have their property `position` set yet.
  55239. * `mesh` ( Mesh ) is the mesh to be digested
  55240. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  55241. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  55242. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  55243. */
  55244. SolidParticleSystem.prototype.digest = function (mesh, options) {
  55245. var size = (options && options.facetNb) || 1;
  55246. var number = (options && options.number);
  55247. var delta = (options && options.delta) || 0;
  55248. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55249. var meshInd = mesh.getIndices();
  55250. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55251. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55252. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55253. var f = 0; // facet counter
  55254. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  55255. // compute size from number
  55256. if (number) {
  55257. number = (number > totalFacets) ? totalFacets : number;
  55258. size = Math.round(totalFacets / number);
  55259. delta = 0;
  55260. }
  55261. else {
  55262. size = (size > totalFacets) ? totalFacets : size;
  55263. }
  55264. var facetPos = []; // submesh positions
  55265. var facetInd = []; // submesh indices
  55266. var facetUV = []; // submesh UV
  55267. var facetCol = []; // submesh colors
  55268. var barycenter = BABYLON.Tmp.Vector3[0];
  55269. var rand;
  55270. var sizeO = size;
  55271. while (f < totalFacets) {
  55272. size = sizeO + Math.floor((1 + delta) * Math.random());
  55273. if (f > totalFacets - size) {
  55274. size = totalFacets - f;
  55275. }
  55276. // reset temp arrays
  55277. facetPos.length = 0;
  55278. facetInd.length = 0;
  55279. facetUV.length = 0;
  55280. facetCol.length = 0;
  55281. // iterate over "size" facets
  55282. var fi = 0;
  55283. for (var j = f * 3; j < (f + size) * 3; j++) {
  55284. facetInd.push(fi);
  55285. var i = meshInd[j];
  55286. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  55287. if (meshUV) {
  55288. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  55289. }
  55290. if (meshCol) {
  55291. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  55292. }
  55293. fi++;
  55294. }
  55295. // create a model shape for each single particle
  55296. var idx = this.nbParticles;
  55297. var shape = this._posToShape(facetPos);
  55298. var shapeUV = this._uvsToShapeUV(facetUV);
  55299. // compute the barycenter of the shape
  55300. var v;
  55301. for (v = 0; v < shape.length; v++) {
  55302. barycenter.addInPlace(shape[v]);
  55303. }
  55304. barycenter.scaleInPlace(1 / shape.length);
  55305. // shift the shape from its barycenter to the origin
  55306. for (v = 0; v < shape.length; v++) {
  55307. shape[v].subtractInPlace(barycenter);
  55308. }
  55309. var bInfo;
  55310. if (this._particlesIntersect) {
  55311. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  55312. }
  55313. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  55314. // add the particle in the SPS
  55315. var currentPos = this._positions.length;
  55316. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  55317. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  55318. // initialize the particle position
  55319. this.particles[this.nbParticles].position.addInPlace(barycenter);
  55320. this._index += shape.length;
  55321. idx++;
  55322. this.nbParticles++;
  55323. this._shapeCounter++;
  55324. f += size;
  55325. }
  55326. return this;
  55327. };
  55328. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  55329. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  55330. var index = 0;
  55331. var idx = 0;
  55332. for (var p = 0; p < this.particles.length; p++) {
  55333. this._particle = this.particles[p];
  55334. this._shape = this._particle._model._shape;
  55335. if (this._particle.rotationQuaternion) {
  55336. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  55337. }
  55338. else {
  55339. this._yaw = this._particle.rotation.y;
  55340. this._pitch = this._particle.rotation.x;
  55341. this._roll = this._particle.rotation.z;
  55342. this._quaternionRotationYPR();
  55343. }
  55344. this._quaternionToRotationMatrix();
  55345. this._rotMatrix.invertToRef(this._invertMatrix);
  55346. for (var pt = 0; pt < this._shape.length; pt++) {
  55347. idx = index + pt * 3;
  55348. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  55349. this._fixedNormal32[idx] = this._normal.x;
  55350. this._fixedNormal32[idx + 1] = this._normal.y;
  55351. this._fixedNormal32[idx + 2] = this._normal.z;
  55352. }
  55353. index = idx + 3;
  55354. }
  55355. };
  55356. //reset copy
  55357. SolidParticleSystem.prototype._resetCopy = function () {
  55358. this._copy.position.x = 0;
  55359. this._copy.position.y = 0;
  55360. this._copy.position.z = 0;
  55361. this._copy.rotation.x = 0;
  55362. this._copy.rotation.y = 0;
  55363. this._copy.rotation.z = 0;
  55364. this._copy.rotationQuaternion = null;
  55365. this._copy.scaling.x = 1;
  55366. this._copy.scaling.y = 1;
  55367. this._copy.scaling.z = 1;
  55368. this._copy.uvs.x = 0;
  55369. this._copy.uvs.y = 0;
  55370. this._copy.uvs.z = 1;
  55371. this._copy.uvs.w = 1;
  55372. this._copy.color = null;
  55373. };
  55374. // _meshBuilder : inserts the shape model in the global SPS mesh
  55375. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  55376. var i;
  55377. var u = 0;
  55378. var c = 0;
  55379. var n = 0;
  55380. this._resetCopy();
  55381. if (options && options.positionFunction) {
  55382. options.positionFunction(this._copy, idx, idxInShape);
  55383. this._mustUnrotateFixedNormals = true;
  55384. }
  55385. if (this._copy.rotationQuaternion) {
  55386. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  55387. }
  55388. else {
  55389. this._yaw = this._copy.rotation.y;
  55390. this._pitch = this._copy.rotation.x;
  55391. this._roll = this._copy.rotation.z;
  55392. this._quaternionRotationYPR();
  55393. }
  55394. this._quaternionToRotationMatrix();
  55395. for (i = 0; i < shape.length; i++) {
  55396. this._vertex.x = shape[i].x;
  55397. this._vertex.y = shape[i].y;
  55398. this._vertex.z = shape[i].z;
  55399. if (options && options.vertexFunction) {
  55400. options.vertexFunction(this._copy, this._vertex, i);
  55401. }
  55402. this._vertex.x *= this._copy.scaling.x;
  55403. this._vertex.y *= this._copy.scaling.y;
  55404. this._vertex.z *= this._copy.scaling.z;
  55405. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  55406. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  55407. if (meshUV) {
  55408. 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);
  55409. u += 2;
  55410. }
  55411. if (this._copy.color) {
  55412. this._color = this._copy.color;
  55413. }
  55414. else if (meshCol && meshCol[c] !== undefined) {
  55415. this._color.r = meshCol[c];
  55416. this._color.g = meshCol[c + 1];
  55417. this._color.b = meshCol[c + 2];
  55418. this._color.a = meshCol[c + 3];
  55419. }
  55420. else {
  55421. this._color.r = 1;
  55422. this._color.g = 1;
  55423. this._color.b = 1;
  55424. this._color.a = 1;
  55425. }
  55426. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  55427. c += 4;
  55428. if (!this.recomputeNormals && meshNor) {
  55429. this._normal.x = meshNor[n];
  55430. this._normal.y = meshNor[n + 1];
  55431. this._normal.z = meshNor[n + 2];
  55432. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  55433. normals.push(this._normal.x, this._normal.y, this._normal.z);
  55434. n += 3;
  55435. }
  55436. }
  55437. for (i = 0; i < meshInd.length; i++) {
  55438. indices.push(p + meshInd[i]);
  55439. }
  55440. if (this._pickable) {
  55441. var nbfaces = meshInd.length / 3;
  55442. for (i = 0; i < nbfaces; i++) {
  55443. this.pickedParticles.push({ idx: idx, faceId: i });
  55444. }
  55445. }
  55446. return this._copy;
  55447. };
  55448. // returns a shape array from positions array
  55449. SolidParticleSystem.prototype._posToShape = function (positions) {
  55450. var shape = [];
  55451. for (var i = 0; i < positions.length; i += 3) {
  55452. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  55453. }
  55454. return shape;
  55455. };
  55456. // returns a shapeUV array from a Vector4 uvs
  55457. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  55458. var shapeUV = [];
  55459. if (uvs) {
  55460. for (var i = 0; i < uvs.length; i++)
  55461. shapeUV.push(uvs[i]);
  55462. }
  55463. return shapeUV;
  55464. };
  55465. // adds a new particle object in the particles array
  55466. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  55467. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  55468. this.particles.push(sp);
  55469. return sp;
  55470. };
  55471. /**
  55472. * Adds some particles to the SPS from the model shape. Returns the shape id.
  55473. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  55474. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  55475. * `nb` (positive integer) the number of particles to be created from this model
  55476. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  55477. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  55478. */
  55479. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  55480. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55481. var meshInd = mesh.getIndices();
  55482. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55483. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55484. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55485. var bbInfo;
  55486. if (this._particlesIntersect) {
  55487. bbInfo = mesh.getBoundingInfo();
  55488. }
  55489. var shape = this._posToShape(meshPos);
  55490. var shapeUV = this._uvsToShapeUV(meshUV);
  55491. var posfunc = options ? options.positionFunction : null;
  55492. var vtxfunc = options ? options.vertexFunction : null;
  55493. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  55494. // particles
  55495. var sp;
  55496. var currentCopy;
  55497. var idx = this.nbParticles;
  55498. for (var i = 0; i < nb; i++) {
  55499. var currentPos = this._positions.length;
  55500. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  55501. if (this._updatable) {
  55502. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  55503. sp.position.copyFrom(currentCopy.position);
  55504. sp.rotation.copyFrom(currentCopy.rotation);
  55505. if (currentCopy.rotationQuaternion) {
  55506. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  55507. }
  55508. if (currentCopy.color) {
  55509. sp.color.copyFrom(currentCopy.color);
  55510. }
  55511. sp.scaling.copyFrom(currentCopy.scaling);
  55512. sp.uvs.copyFrom(currentCopy.uvs);
  55513. }
  55514. this._index += shape.length;
  55515. idx++;
  55516. }
  55517. this.nbParticles += nb;
  55518. this._shapeCounter++;
  55519. return this._shapeCounter - 1;
  55520. };
  55521. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  55522. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  55523. this._resetCopy();
  55524. if (particle._model._positionFunction) {
  55525. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  55526. }
  55527. if (this._copy.rotationQuaternion) {
  55528. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  55529. }
  55530. else {
  55531. this._yaw = this._copy.rotation.y;
  55532. this._pitch = this._copy.rotation.x;
  55533. this._roll = this._copy.rotation.z;
  55534. this._quaternionRotationYPR();
  55535. }
  55536. this._quaternionToRotationMatrix();
  55537. this._shape = particle._model._shape;
  55538. for (var pt = 0; pt < this._shape.length; pt++) {
  55539. this._vertex.x = this._shape[pt].x;
  55540. this._vertex.y = this._shape[pt].y;
  55541. this._vertex.z = this._shape[pt].z;
  55542. if (particle._model._vertexFunction) {
  55543. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  55544. }
  55545. this._vertex.x *= this._copy.scaling.x;
  55546. this._vertex.y *= this._copy.scaling.y;
  55547. this._vertex.z *= this._copy.scaling.z;
  55548. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  55549. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  55550. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  55551. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  55552. }
  55553. particle.position.x = 0.0;
  55554. particle.position.y = 0.0;
  55555. particle.position.z = 0.0;
  55556. particle.rotation.x = 0.0;
  55557. particle.rotation.y = 0.0;
  55558. particle.rotation.z = 0.0;
  55559. particle.rotationQuaternion = null;
  55560. particle.scaling.x = 1.0;
  55561. particle.scaling.y = 1.0;
  55562. particle.scaling.z = 1.0;
  55563. };
  55564. /**
  55565. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  55566. * Returns the SPS.
  55567. */
  55568. SolidParticleSystem.prototype.rebuildMesh = function () {
  55569. for (var p = 0; p < this.particles.length; p++) {
  55570. this._rebuildParticle(this.particles[p]);
  55571. }
  55572. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  55573. return this;
  55574. };
  55575. /**
  55576. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  55577. * This method calls `updateParticle()` for each particle of the SPS.
  55578. * For an animated SPS, it is usually called within the render loop.
  55579. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  55580. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  55581. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  55582. * Returns the SPS.
  55583. */
  55584. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  55585. if (start === void 0) { start = 0; }
  55586. if (end === void 0) { end = this.nbParticles - 1; }
  55587. if (update === void 0) { update = true; }
  55588. if (!this._updatable) {
  55589. return;
  55590. }
  55591. // custom beforeUpdate
  55592. this.beforeUpdateParticles(start, end, update);
  55593. this._cam_axisX.x = 1.0;
  55594. this._cam_axisX.y = 0.0;
  55595. this._cam_axisX.z = 0.0;
  55596. this._cam_axisY.x = 0.0;
  55597. this._cam_axisY.y = 1.0;
  55598. this._cam_axisY.z = 0.0;
  55599. this._cam_axisZ.x = 0.0;
  55600. this._cam_axisZ.y = 0.0;
  55601. this._cam_axisZ.z = 1.0;
  55602. // if the particles will always face the camera
  55603. if (this.billboard) {
  55604. this.mesh.computeWorldMatrix(true);
  55605. // compute the camera position and un-rotate it by the current mesh rotation
  55606. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  55607. this._quaternionToRotationMatrix();
  55608. this._rotMatrix.invertToRef(this._invertMatrix);
  55609. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  55610. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  55611. this._cam_axisZ.normalize();
  55612. // same for camera up vector extracted from the cam view matrix
  55613. var view = this._camera.getViewMatrix(true);
  55614. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  55615. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  55616. this._cam_axisY.normalize();
  55617. this._cam_axisX.normalize();
  55618. }
  55619. }
  55620. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  55621. var idx = 0; // current position index in the global array positions32
  55622. var index = 0; // position start index in the global array positions32 of the current particle
  55623. var colidx = 0; // current color index in the global array colors32
  55624. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  55625. var uvidx = 0; // current uv index in the global array uvs32
  55626. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  55627. var pt = 0; // current index in the particle model shape
  55628. if (this.mesh.isFacetDataEnabled) {
  55629. this._computeBoundingBox = true;
  55630. }
  55631. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  55632. if (this._computeBoundingBox) {
  55633. if (start == 0 && end == this.nbParticles - 1) {
  55634. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  55635. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  55636. }
  55637. else {
  55638. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  55639. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  55640. }
  55641. }
  55642. // particle loop
  55643. index = this.particles[start]._pos;
  55644. var vpos = (index / 3) | 0;
  55645. colorIndex = vpos * 4;
  55646. uvIndex = vpos * 2;
  55647. for (var p = start; p <= end; p++) {
  55648. this._particle = this.particles[p];
  55649. this._shape = this._particle._model._shape;
  55650. this._shapeUV = this._particle._model._shapeUV;
  55651. // call to custom user function to update the particle properties
  55652. this.updateParticle(this._particle);
  55653. if (this._particle.isVisible) {
  55654. // particle rotation matrix
  55655. if (this.billboard) {
  55656. this._particle.rotation.x = 0.0;
  55657. this._particle.rotation.y = 0.0;
  55658. }
  55659. if (this._computeParticleRotation || this.billboard) {
  55660. if (this._particle.rotationQuaternion) {
  55661. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  55662. }
  55663. else {
  55664. this._yaw = this._particle.rotation.y;
  55665. this._pitch = this._particle.rotation.x;
  55666. this._roll = this._particle.rotation.z;
  55667. this._quaternionRotationYPR();
  55668. }
  55669. this._quaternionToRotationMatrix();
  55670. }
  55671. // particle vertex loop
  55672. for (pt = 0; pt < this._shape.length; pt++) {
  55673. idx = index + pt * 3;
  55674. colidx = colorIndex + pt * 4;
  55675. uvidx = uvIndex + pt * 2;
  55676. this._vertex.x = this._shape[pt].x;
  55677. this._vertex.y = this._shape[pt].y;
  55678. this._vertex.z = this._shape[pt].z;
  55679. if (this._computeParticleVertex) {
  55680. this.updateParticleVertex(this._particle, this._vertex, pt);
  55681. }
  55682. // positions
  55683. this._vertex.x *= this._particle.scaling.x;
  55684. this._vertex.y *= this._particle.scaling.y;
  55685. this._vertex.z *= this._particle.scaling.z;
  55686. 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];
  55687. 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;
  55688. 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;
  55689. 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;
  55690. 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;
  55691. 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;
  55692. 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;
  55693. if (this._computeBoundingBox) {
  55694. if (this._positions32[idx] < this._minimum.x) {
  55695. this._minimum.x = this._positions32[idx];
  55696. }
  55697. if (this._positions32[idx] > this._maximum.x) {
  55698. this._maximum.x = this._positions32[idx];
  55699. }
  55700. if (this._positions32[idx + 1] < this._minimum.y) {
  55701. this._minimum.y = this._positions32[idx + 1];
  55702. }
  55703. if (this._positions32[idx + 1] > this._maximum.y) {
  55704. this._maximum.y = this._positions32[idx + 1];
  55705. }
  55706. if (this._positions32[idx + 2] < this._minimum.z) {
  55707. this._minimum.z = this._positions32[idx + 2];
  55708. }
  55709. if (this._positions32[idx + 2] > this._maximum.z) {
  55710. this._maximum.z = this._positions32[idx + 2];
  55711. }
  55712. }
  55713. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  55714. if (!this._computeParticleVertex) {
  55715. this._normal.x = this._fixedNormal32[idx];
  55716. this._normal.y = this._fixedNormal32[idx + 1];
  55717. this._normal.z = this._fixedNormal32[idx + 2];
  55718. 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]);
  55719. 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]);
  55720. 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]);
  55721. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  55722. 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;
  55723. 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;
  55724. }
  55725. if (this._computeParticleColor) {
  55726. this._colors32[colidx] = this._particle.color.r;
  55727. this._colors32[colidx + 1] = this._particle.color.g;
  55728. this._colors32[colidx + 2] = this._particle.color.b;
  55729. this._colors32[colidx + 3] = this._particle.color.a;
  55730. }
  55731. if (this._computeParticleTexture) {
  55732. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  55733. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  55734. }
  55735. }
  55736. }
  55737. else {
  55738. for (pt = 0; pt < this._shape.length; pt++) {
  55739. idx = index + pt * 3;
  55740. colidx = colorIndex + pt * 4;
  55741. uvidx = uvIndex + pt * 2;
  55742. this._positions32[idx] = this._camera.position.x;
  55743. this._positions32[idx + 1] = this._camera.position.y;
  55744. this._positions32[idx + 2] = this._camera.position.z;
  55745. this._normals32[idx] = 0.0;
  55746. this._normals32[idx + 1] = 0.0;
  55747. this._normals32[idx + 2] = 0.0;
  55748. if (this._computeParticleColor) {
  55749. this._colors32[colidx] = this._particle.color.r;
  55750. this._colors32[colidx + 1] = this._particle.color.g;
  55751. this._colors32[colidx + 2] = this._particle.color.b;
  55752. this._colors32[colidx + 3] = this._particle.color.a;
  55753. }
  55754. if (this._computeParticleTexture) {
  55755. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  55756. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  55757. }
  55758. }
  55759. }
  55760. // if the particle intersections must be computed : update the bbInfo
  55761. if (this._particlesIntersect) {
  55762. var bInfo = this._particle._boundingInfo;
  55763. var bBox = bInfo.boundingBox;
  55764. var bSphere = bInfo.boundingSphere;
  55765. if (!this._bSphereOnly) {
  55766. // place, scale and rotate the particle bbox within the SPS local system, then update it
  55767. for (var b = 0; b < bBox.vectors.length; b++) {
  55768. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  55769. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  55770. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  55771. 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];
  55772. 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;
  55773. 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;
  55774. 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;
  55775. 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;
  55776. 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;
  55777. 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;
  55778. }
  55779. bBox._update(this.mesh._worldMatrix);
  55780. }
  55781. // place and scale the particle bouding sphere in the SPS local system, then update it
  55782. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  55783. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  55784. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  55785. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  55786. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  55787. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  55788. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  55789. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  55790. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  55791. 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));
  55792. bSphere._update(this.mesh._worldMatrix);
  55793. }
  55794. // increment indexes for the next particle
  55795. index = idx + 3;
  55796. colorIndex = colidx + 4;
  55797. uvIndex = uvidx + 2;
  55798. }
  55799. // if the VBO must be updated
  55800. if (update) {
  55801. if (this._computeParticleColor) {
  55802. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  55803. }
  55804. if (this._computeParticleTexture) {
  55805. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  55806. }
  55807. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  55808. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  55809. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  55810. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  55811. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  55812. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  55813. for (var i = 0; i < this._normals32.length; i++) {
  55814. this._fixedNormal32[i] = this._normals32[i];
  55815. }
  55816. }
  55817. if (!this.mesh.areNormalsFrozen) {
  55818. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  55819. }
  55820. }
  55821. }
  55822. if (this._computeBoundingBox) {
  55823. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  55824. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  55825. }
  55826. this.afterUpdateParticles(start, end, update);
  55827. return this;
  55828. };
  55829. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  55830. this._halfroll = this._roll * 0.5;
  55831. this._halfpitch = this._pitch * 0.5;
  55832. this._halfyaw = this._yaw * 0.5;
  55833. this._sinRoll = Math.sin(this._halfroll);
  55834. this._cosRoll = Math.cos(this._halfroll);
  55835. this._sinPitch = Math.sin(this._halfpitch);
  55836. this._cosPitch = Math.cos(this._halfpitch);
  55837. this._sinYaw = Math.sin(this._halfyaw);
  55838. this._cosYaw = Math.cos(this._halfyaw);
  55839. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  55840. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  55841. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  55842. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  55843. };
  55844. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  55845. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  55846. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  55847. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  55848. this._rotMatrix.m[3] = 0;
  55849. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  55850. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  55851. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  55852. this._rotMatrix.m[7] = 0;
  55853. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  55854. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  55855. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  55856. this._rotMatrix.m[11] = 0;
  55857. this._rotMatrix.m[12] = 0;
  55858. this._rotMatrix.m[13] = 0;
  55859. this._rotMatrix.m[14] = 0;
  55860. this._rotMatrix.m[15] = 1.0;
  55861. };
  55862. /**
  55863. * Disposes the SPS.
  55864. * Returns nothing.
  55865. */
  55866. SolidParticleSystem.prototype.dispose = function () {
  55867. this.mesh.dispose();
  55868. this.vars = null;
  55869. // drop references to internal big arrays for the GC
  55870. this._positions = null;
  55871. this._indices = null;
  55872. this._normals = null;
  55873. this._uvs = null;
  55874. this._colors = null;
  55875. this._positions32 = null;
  55876. this._normals32 = null;
  55877. this._fixedNormal32 = null;
  55878. this._uvs32 = null;
  55879. this._colors32 = null;
  55880. this.pickedParticles = null;
  55881. };
  55882. /**
  55883. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  55884. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55885. * Returns the SPS.
  55886. */
  55887. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  55888. if (!this._isVisibilityBoxLocked) {
  55889. this.mesh.refreshBoundingInfo();
  55890. }
  55891. return this;
  55892. };
  55893. /**
  55894. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  55895. * @param size the size (float) of the visibility box
  55896. * note : this doesn't lock the SPS mesh bounding box.
  55897. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55898. */
  55899. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  55900. var vis = size / 2;
  55901. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  55902. };
  55903. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  55904. // getter and setter
  55905. get: function () {
  55906. return this._alwaysVisible;
  55907. },
  55908. /**
  55909. * Sets the SPS as always visible or not
  55910. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55911. */
  55912. set: function (val) {
  55913. this._alwaysVisible = val;
  55914. this.mesh.alwaysSelectAsActiveMesh = val;
  55915. },
  55916. enumerable: true,
  55917. configurable: true
  55918. });
  55919. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  55920. get: function () {
  55921. return this._isVisibilityBoxLocked;
  55922. },
  55923. /**
  55924. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55925. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55926. */
  55927. set: function (val) {
  55928. this._isVisibilityBoxLocked = val;
  55929. this.mesh.getBoundingInfo().isLocked = val;
  55930. },
  55931. enumerable: true,
  55932. configurable: true
  55933. });
  55934. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  55935. // getters
  55936. get: function () {
  55937. return this._computeParticleRotation;
  55938. },
  55939. // Optimizer setters
  55940. /**
  55941. * Tells to `setParticles()` to compute the particle rotations or not.
  55942. * Default value : true. The SPS is faster when it's set to false.
  55943. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55944. */
  55945. set: function (val) {
  55946. this._computeParticleRotation = val;
  55947. },
  55948. enumerable: true,
  55949. configurable: true
  55950. });
  55951. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  55952. get: function () {
  55953. return this._computeParticleColor;
  55954. },
  55955. /**
  55956. * Tells to `setParticles()` to compute the particle colors or not.
  55957. * Default value : true. The SPS is faster when it's set to false.
  55958. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55959. */
  55960. set: function (val) {
  55961. this._computeParticleColor = val;
  55962. },
  55963. enumerable: true,
  55964. configurable: true
  55965. });
  55966. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  55967. get: function () {
  55968. return this._computeParticleTexture;
  55969. },
  55970. /**
  55971. * Tells to `setParticles()` to compute the particle textures or not.
  55972. * Default value : true. The SPS is faster when it's set to false.
  55973. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  55974. */
  55975. set: function (val) {
  55976. this._computeParticleTexture = val;
  55977. },
  55978. enumerable: true,
  55979. configurable: true
  55980. });
  55981. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  55982. get: function () {
  55983. return this._computeParticleVertex;
  55984. },
  55985. /**
  55986. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  55987. * Default value : false. The SPS is faster when it's set to false.
  55988. * Note : the particle custom vertex positions aren't stored values.
  55989. */
  55990. set: function (val) {
  55991. this._computeParticleVertex = val;
  55992. },
  55993. enumerable: true,
  55994. configurable: true
  55995. });
  55996. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  55997. get: function () {
  55998. return this._computeBoundingBox;
  55999. },
  56000. /**
  56001. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  56002. */
  56003. set: function (val) {
  56004. this._computeBoundingBox = val;
  56005. },
  56006. enumerable: true,
  56007. configurable: true
  56008. });
  56009. // =======================================================================
  56010. // Particle behavior logic
  56011. // these following methods may be overwritten by the user to fit his needs
  56012. /**
  56013. * This function does nothing. It may be overwritten to set all the particle first values.
  56014. * The SPS doesn't call this function, you may have to call it by your own.
  56015. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  56016. */
  56017. SolidParticleSystem.prototype.initParticles = function () {
  56018. };
  56019. /**
  56020. * This function does nothing. It may be overwritten to recycle a particle.
  56021. * The SPS doesn't call this function, you may have to call it by your own.
  56022. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  56023. */
  56024. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  56025. return particle;
  56026. };
  56027. /**
  56028. * Updates a particle : this function should be overwritten by the user.
  56029. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  56030. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  56031. * ex : just set a particle position or velocity and recycle conditions
  56032. */
  56033. SolidParticleSystem.prototype.updateParticle = function (particle) {
  56034. return particle;
  56035. };
  56036. /**
  56037. * Updates a vertex of a particle : it can be overwritten by the user.
  56038. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  56039. * @param particle the current particle
  56040. * @param vertex the current index of the current particle
  56041. * @param pt the index of the current vertex in the particle shape
  56042. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  56043. * ex : just set a vertex particle position
  56044. */
  56045. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  56046. return vertex;
  56047. };
  56048. /**
  56049. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  56050. * This does nothing and may be overwritten by the user.
  56051. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56052. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56053. * @param update the boolean update value actually passed to setParticles()
  56054. */
  56055. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  56056. };
  56057. /**
  56058. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  56059. * This will be passed three parameters.
  56060. * This does nothing and may be overwritten by the user.
  56061. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56062. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56063. * @param update the boolean update value actually passed to setParticles()
  56064. */
  56065. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  56066. };
  56067. return SolidParticleSystem;
  56068. }());
  56069. BABYLON.SolidParticleSystem = SolidParticleSystem;
  56070. })(BABYLON || (BABYLON = {}));
  56071. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  56072. var BABYLON;
  56073. (function (BABYLON) {
  56074. var Internals;
  56075. (function (Internals) {
  56076. var FileFaceOrientation = (function () {
  56077. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  56078. this.name = name;
  56079. this.worldAxisForNormal = worldAxisForNormal;
  56080. this.worldAxisForFileX = worldAxisForFileX;
  56081. this.worldAxisForFileY = worldAxisForFileY;
  56082. }
  56083. return FileFaceOrientation;
  56084. }());
  56085. ;
  56086. /**
  56087. * Helper class dealing with the extraction of spherical polynomial dataArray
  56088. * from a cube map.
  56089. */
  56090. var CubeMapToSphericalPolynomialTools = (function () {
  56091. function CubeMapToSphericalPolynomialTools() {
  56092. }
  56093. /**
  56094. * Converts a cubemap to the according Spherical Polynomial data.
  56095. * This extracts the first 3 orders only as they are the only one used in the lighting.
  56096. *
  56097. * @param cubeInfo The Cube map to extract the information from.
  56098. * @return The Spherical Polynomial data.
  56099. */
  56100. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  56101. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  56102. var totalSolidAngle = 0.0;
  56103. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  56104. var du = 2.0 / cubeInfo.size;
  56105. var dv = du;
  56106. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  56107. var minUV = du * 0.5 - 1.0;
  56108. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56109. var fileFace = this.FileFaces[faceIndex];
  56110. var dataArray = cubeInfo[fileFace.name];
  56111. var v = minUV;
  56112. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  56113. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  56114. // Because SP is still linear, so summation is fine in that basis.
  56115. for (var y = 0; y < cubeInfo.size; y++) {
  56116. var u = minUV;
  56117. for (var x = 0; x < cubeInfo.size; x++) {
  56118. // World direction (not normalised)
  56119. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  56120. worldDirection.normalize();
  56121. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  56122. if (1) {
  56123. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  56124. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  56125. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  56126. var color = new BABYLON.Color3(r, g, b);
  56127. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  56128. }
  56129. else {
  56130. if (faceIndex == 0) {
  56131. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56132. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56133. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56134. }
  56135. else if (faceIndex == 1) {
  56136. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56137. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56138. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56139. }
  56140. else if (faceIndex == 2) {
  56141. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56142. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56143. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56144. }
  56145. else if (faceIndex == 3) {
  56146. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56147. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56148. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56149. }
  56150. else if (faceIndex == 4) {
  56151. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56152. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56153. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56154. }
  56155. else if (faceIndex == 5) {
  56156. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56157. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56158. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56159. }
  56160. 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]);
  56161. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  56162. }
  56163. totalSolidAngle += deltaSolidAngle;
  56164. u += du;
  56165. }
  56166. v += dv;
  56167. }
  56168. }
  56169. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  56170. var correction = correctSolidAngle / totalSolidAngle;
  56171. sphericalHarmonics.scale(correction);
  56172. // Additionally scale by pi -- audit needed
  56173. sphericalHarmonics.scale(1.0 / Math.PI);
  56174. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  56175. };
  56176. return CubeMapToSphericalPolynomialTools;
  56177. }());
  56178. CubeMapToSphericalPolynomialTools.FileFaces = [
  56179. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  56180. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  56181. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  56182. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  56183. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  56184. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  56185. ];
  56186. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  56187. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56188. })(BABYLON || (BABYLON = {}));
  56189. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  56190. var BABYLON;
  56191. (function (BABYLON) {
  56192. var Internals;
  56193. (function (Internals) {
  56194. /**
  56195. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  56196. */
  56197. var PanoramaToCubeMapTools = (function () {
  56198. function PanoramaToCubeMapTools() {
  56199. }
  56200. /**
  56201. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  56202. *
  56203. * @param float32Array The source data.
  56204. * @param inputWidth The width of the input panorama.
  56205. * @param inputhHeight The height of the input panorama.
  56206. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  56207. * @return The cubemap data
  56208. */
  56209. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  56210. if (!float32Array) {
  56211. throw "ConvertPanoramaToCubemap: input cannot be null";
  56212. }
  56213. if (float32Array.length != inputWidth * inputHeight * 3) {
  56214. throw "ConvertPanoramaToCubemap: input size is wrong";
  56215. }
  56216. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  56217. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  56218. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  56219. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  56220. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  56221. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  56222. return {
  56223. front: textureFront,
  56224. back: textureBack,
  56225. left: textureLeft,
  56226. right: textureRight,
  56227. up: textureUp,
  56228. down: textureDown,
  56229. size: size
  56230. };
  56231. };
  56232. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  56233. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  56234. var textureArray = new Float32Array(buffer);
  56235. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  56236. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  56237. var dy = 1 / texSize;
  56238. var fy = 0;
  56239. for (var y = 0; y < texSize; y++) {
  56240. var xv1 = faceData[0];
  56241. var xv2 = faceData[2];
  56242. for (var x = 0; x < texSize; x++) {
  56243. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  56244. v.normalize();
  56245. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  56246. // 3 channels per pixels
  56247. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  56248. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  56249. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  56250. xv1 = xv1.add(rotDX1);
  56251. xv2 = xv2.add(rotDX2);
  56252. }
  56253. fy += dy;
  56254. }
  56255. return textureArray;
  56256. };
  56257. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  56258. var theta = Math.atan2(vDir.z, vDir.x);
  56259. var phi = Math.acos(vDir.y);
  56260. while (theta < -Math.PI)
  56261. theta += 2 * Math.PI;
  56262. while (theta > Math.PI)
  56263. theta -= 2 * Math.PI;
  56264. var dx = theta / Math.PI;
  56265. var dy = phi / Math.PI;
  56266. // recenter.
  56267. dx = dx * 0.5 + 0.5;
  56268. var px = Math.round(dx * inputWidth);
  56269. if (px < 0)
  56270. px = 0;
  56271. else if (px >= inputWidth)
  56272. px = inputWidth - 1;
  56273. var py = Math.round(dy * inputHeight);
  56274. if (py < 0)
  56275. py = 0;
  56276. else if (py >= inputHeight)
  56277. py = inputHeight - 1;
  56278. var inputY = (inputHeight - py - 1);
  56279. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  56280. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  56281. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  56282. return {
  56283. r: r,
  56284. g: g,
  56285. b: b
  56286. };
  56287. };
  56288. return PanoramaToCubeMapTools;
  56289. }());
  56290. PanoramaToCubeMapTools.FACE_FRONT = [
  56291. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56292. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56293. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56294. new BABYLON.Vector3(1.0, 1.0, -1.0)
  56295. ];
  56296. PanoramaToCubeMapTools.FACE_BACK = [
  56297. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56298. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56299. new BABYLON.Vector3(1.0, 1.0, 1.0),
  56300. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  56301. ];
  56302. PanoramaToCubeMapTools.FACE_RIGHT = [
  56303. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56304. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56305. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56306. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56307. ];
  56308. PanoramaToCubeMapTools.FACE_LEFT = [
  56309. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56310. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56311. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56312. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  56313. ];
  56314. PanoramaToCubeMapTools.FACE_DOWN = [
  56315. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56316. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56317. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56318. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56319. ];
  56320. PanoramaToCubeMapTools.FACE_UP = [
  56321. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56322. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56323. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56324. new BABYLON.Vector3(1.0, -1.0, -1.0)
  56325. ];
  56326. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  56327. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56328. })(BABYLON || (BABYLON = {}));
  56329. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  56330. var BABYLON;
  56331. (function (BABYLON) {
  56332. var Internals;
  56333. (function (Internals) {
  56334. ;
  56335. /**
  56336. * This groups tools to convert HDR texture to native colors array.
  56337. */
  56338. var HDRTools = (function () {
  56339. function HDRTools() {
  56340. }
  56341. HDRTools.Ldexp = function (mantissa, exponent) {
  56342. if (exponent > 1023) {
  56343. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  56344. }
  56345. if (exponent < -1074) {
  56346. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  56347. }
  56348. return mantissa * Math.pow(2, exponent);
  56349. };
  56350. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  56351. if (exponent > 0) {
  56352. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  56353. float32array[index + 0] = red * exponent;
  56354. float32array[index + 1] = green * exponent;
  56355. float32array[index + 2] = blue * exponent;
  56356. }
  56357. else {
  56358. float32array[index + 0] = 0;
  56359. float32array[index + 1] = 0;
  56360. float32array[index + 2] = 0;
  56361. }
  56362. };
  56363. HDRTools.readStringLine = function (uint8array, startIndex) {
  56364. var line = "";
  56365. var character = "";
  56366. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  56367. character = String.fromCharCode(uint8array[i]);
  56368. if (character == "\n") {
  56369. break;
  56370. }
  56371. line += character;
  56372. }
  56373. return line;
  56374. };
  56375. /**
  56376. * Reads header information from an RGBE texture stored in a native array.
  56377. * More information on this format are available here:
  56378. * https://en.wikipedia.org/wiki/RGBE_image_format
  56379. *
  56380. * @param uint8array The binary file stored in native array.
  56381. * @return The header information.
  56382. */
  56383. HDRTools.RGBE_ReadHeader = function (uint8array) {
  56384. var height = 0;
  56385. var width = 0;
  56386. var line = this.readStringLine(uint8array, 0);
  56387. if (line[0] != '#' || line[1] != '?') {
  56388. throw "Bad HDR Format.";
  56389. }
  56390. var endOfHeader = false;
  56391. var findFormat = false;
  56392. var lineIndex = 0;
  56393. do {
  56394. lineIndex += (line.length + 1);
  56395. line = this.readStringLine(uint8array, lineIndex);
  56396. if (line == "FORMAT=32-bit_rle_rgbe") {
  56397. findFormat = true;
  56398. }
  56399. else if (line.length == 0) {
  56400. endOfHeader = true;
  56401. }
  56402. } while (!endOfHeader);
  56403. if (!findFormat) {
  56404. throw "HDR Bad header format, unsupported FORMAT";
  56405. }
  56406. lineIndex += (line.length + 1);
  56407. line = this.readStringLine(uint8array, lineIndex);
  56408. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  56409. var match = sizeRegexp.exec(line);
  56410. // TODO. Support +Y and -X if needed.
  56411. if (match.length < 3) {
  56412. throw "HDR Bad header format, no size";
  56413. }
  56414. width = parseInt(match[2]);
  56415. height = parseInt(match[1]);
  56416. if (width < 8 || width > 0x7fff) {
  56417. throw "HDR Bad header format, unsupported size";
  56418. }
  56419. lineIndex += (line.length + 1);
  56420. return {
  56421. height: height,
  56422. width: width,
  56423. dataPosition: lineIndex
  56424. };
  56425. };
  56426. /**
  56427. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  56428. * This RGBE texture needs to store the information as a panorama.
  56429. *
  56430. * More information on this format are available here:
  56431. * https://en.wikipedia.org/wiki/RGBE_image_format
  56432. *
  56433. * @param buffer The binary file stored in an array buffer.
  56434. * @param size The expected size of the extracted cubemap.
  56435. * @return The Cube Map information.
  56436. */
  56437. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  56438. var uint8array = new Uint8Array(buffer);
  56439. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  56440. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56441. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  56442. return cubeMapData;
  56443. };
  56444. /**
  56445. * Returns the pixels data extracted from an RGBE texture.
  56446. * This pixels will be stored left to right up to down in the R G B order in one array.
  56447. *
  56448. * More information on this format are available here:
  56449. * https://en.wikipedia.org/wiki/RGBE_image_format
  56450. *
  56451. * @param uint8array The binary file stored in an array buffer.
  56452. * @param hdrInfo The header information of the file.
  56453. * @return The pixels data in RGB right to left up to down order.
  56454. */
  56455. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  56456. // Keep for multi format supports.
  56457. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56458. };
  56459. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  56460. var num_scanlines = hdrInfo.height;
  56461. var scanline_width = hdrInfo.width;
  56462. var a, b, c, d, count;
  56463. var dataIndex = hdrInfo.dataPosition;
  56464. var index = 0, endIndex = 0, i = 0;
  56465. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  56466. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  56467. // 3 channels of 4 bytes per pixel in float.
  56468. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  56469. var resultArray = new Float32Array(resultBuffer);
  56470. // read in each successive scanline
  56471. while (num_scanlines > 0) {
  56472. a = uint8array[dataIndex++];
  56473. b = uint8array[dataIndex++];
  56474. c = uint8array[dataIndex++];
  56475. d = uint8array[dataIndex++];
  56476. if (a != 2 || b != 2 || (c & 0x80)) {
  56477. // this file is not run length encoded
  56478. throw "HDR Bad header format, not RLE";
  56479. }
  56480. if (((c << 8) | d) != scanline_width) {
  56481. throw "HDR Bad header format, wrong scan line width";
  56482. }
  56483. index = 0;
  56484. // read each of the four channels for the scanline into the buffer
  56485. for (i = 0; i < 4; i++) {
  56486. endIndex = (i + 1) * scanline_width;
  56487. while (index < endIndex) {
  56488. a = uint8array[dataIndex++];
  56489. b = uint8array[dataIndex++];
  56490. if (a > 128) {
  56491. // a run of the same value
  56492. count = a - 128;
  56493. if ((count == 0) || (count > endIndex - index)) {
  56494. throw "HDR Bad Format, bad scanline data (run)";
  56495. }
  56496. while (count-- > 0) {
  56497. scanLineArray[index++] = b;
  56498. }
  56499. }
  56500. else {
  56501. // a non-run
  56502. count = a;
  56503. if ((count == 0) || (count > endIndex - index)) {
  56504. throw "HDR Bad Format, bad scanline data (non-run)";
  56505. }
  56506. scanLineArray[index++] = b;
  56507. if (--count > 0) {
  56508. for (var j = 0; j < count; j++) {
  56509. scanLineArray[index++] = uint8array[dataIndex++];
  56510. }
  56511. }
  56512. }
  56513. }
  56514. }
  56515. // now convert data from buffer into floats
  56516. for (i = 0; i < scanline_width; i++) {
  56517. a = scanLineArray[i];
  56518. b = scanLineArray[i + scanline_width];
  56519. c = scanLineArray[i + 2 * scanline_width];
  56520. d = scanLineArray[i + 3 * scanline_width];
  56521. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  56522. }
  56523. num_scanlines--;
  56524. }
  56525. return resultArray;
  56526. };
  56527. return HDRTools;
  56528. }());
  56529. Internals.HDRTools = HDRTools;
  56530. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56531. })(BABYLON || (BABYLON = {}));
  56532. //# sourceMappingURL=babylon.tools.hdr.js.map
  56533. //_______________________________________________________________
  56534. // Extracted from CubeMapGen:
  56535. // https://code.google.com/archive/p/cubemapgen/
  56536. //
  56537. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  56538. //_______________________________________________________________
  56539. var BABYLON;
  56540. (function (BABYLON) {
  56541. var Internals;
  56542. (function (Internals) {
  56543. /**
  56544. * The bounding box information used during the conversion process.
  56545. */
  56546. var CMGBoundinBox = (function () {
  56547. function CMGBoundinBox() {
  56548. this.min = new BABYLON.Vector3(0, 0, 0);
  56549. this.max = new BABYLON.Vector3(0, 0, 0);
  56550. this.clear();
  56551. }
  56552. CMGBoundinBox.prototype.clear = function () {
  56553. this.min.x = CMGBoundinBox.MAX;
  56554. this.min.y = CMGBoundinBox.MAX;
  56555. this.min.z = CMGBoundinBox.MAX;
  56556. this.max.x = CMGBoundinBox.MIN;
  56557. this.max.y = CMGBoundinBox.MIN;
  56558. this.max.z = CMGBoundinBox.MIN;
  56559. };
  56560. CMGBoundinBox.prototype.augment = function (x, y, z) {
  56561. this.min.x = Math.min(this.min.x, x);
  56562. this.min.y = Math.min(this.min.y, y);
  56563. this.min.z = Math.min(this.min.z, z);
  56564. this.max.x = Math.max(this.max.x, x);
  56565. this.max.y = Math.max(this.max.y, y);
  56566. this.max.z = Math.max(this.max.z, z);
  56567. };
  56568. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  56569. this.min.x = Math.max(this.min.x, x);
  56570. this.min.y = Math.max(this.min.y, y);
  56571. this.min.z = Math.max(this.min.z, z);
  56572. };
  56573. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  56574. this.max.x = Math.min(this.max.x, x);
  56575. this.max.y = Math.min(this.max.y, y);
  56576. this.max.z = Math.min(this.max.z, z);
  56577. };
  56578. CMGBoundinBox.prototype.empty = function () {
  56579. if ((this.min.x > this.max.y) ||
  56580. (this.min.y > this.max.y) ||
  56581. (this.min.z > this.max.y)) {
  56582. return true;
  56583. }
  56584. else {
  56585. return false;
  56586. }
  56587. };
  56588. return CMGBoundinBox;
  56589. }());
  56590. CMGBoundinBox.MAX = Number.MAX_VALUE;
  56591. CMGBoundinBox.MIN = Number.MIN_VALUE;
  56592. /**
  56593. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  56594. * required by the glossinees of a material.
  56595. *
  56596. * This only supports the cosine drop power as well as Warp fixup generation method.
  56597. *
  56598. * This is using the process from CubeMapGen described here:
  56599. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  56600. */
  56601. var PMREMGenerator = (function () {
  56602. /**
  56603. * Constructor of the generator.
  56604. *
  56605. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  56606. * @param inputSize The size of the cubemap faces
  56607. * @param outputSize The size of the output cubemap faces
  56608. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  56609. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  56610. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  56611. * @param specularPower The max specular level of the desired cubemap
  56612. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  56613. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  56614. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  56615. */
  56616. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  56617. this.input = input;
  56618. this.inputSize = inputSize;
  56619. this.outputSize = outputSize;
  56620. this.maxNumMipLevels = maxNumMipLevels;
  56621. this.numChannels = numChannels;
  56622. this.isFloat = isFloat;
  56623. this.specularPower = specularPower;
  56624. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  56625. this.excludeBase = excludeBase;
  56626. this.fixup = fixup;
  56627. this._outputSurface = [];
  56628. this._numMipLevels = 0;
  56629. }
  56630. /**
  56631. * Launches the filter process and return the result.
  56632. *
  56633. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  56634. */
  56635. PMREMGenerator.prototype.filterCubeMap = function () {
  56636. // Init cubemap processor
  56637. this.init();
  56638. // Filters the cubemap
  56639. this.filterCubeMapMipChain();
  56640. // Returns the filtered mips.
  56641. return this._outputSurface;
  56642. };
  56643. PMREMGenerator.prototype.init = function () {
  56644. var i;
  56645. var j;
  56646. var mipLevelSize;
  56647. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  56648. if (this.maxNumMipLevels == 0) {
  56649. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  56650. }
  56651. //first miplevel size
  56652. mipLevelSize = this.outputSize;
  56653. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  56654. for (j = 0; j < this.maxNumMipLevels; j++) {
  56655. this._outputSurface.length++;
  56656. this._outputSurface[j] = [];
  56657. //Iterate over faces for output images
  56658. for (i = 0; i < 6; i++) {
  56659. this._outputSurface[j].length++;
  56660. // Initializes a new array for the output.
  56661. if (this.isFloat) {
  56662. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  56663. }
  56664. else {
  56665. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  56666. }
  56667. }
  56668. //next mip level is half size
  56669. mipLevelSize >>= 1;
  56670. this._numMipLevels++;
  56671. //terminate if mip chain becomes too small
  56672. if (mipLevelSize == 0) {
  56673. this.maxNumMipLevels = j;
  56674. return;
  56675. }
  56676. }
  56677. };
  56678. //--------------------------------------------------------------------------------------
  56679. //Cube map filtering and mip chain generation.
  56680. // the cube map filtereing is specified using a number of parameters:
  56681. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  56682. // indicates the region of the hemisphere to filter over for each tap.
  56683. //
  56684. // Note that the top mip level is also a filtered version of the original input images
  56685. // as well in order to create mip chains for diffuse environment illumination.
  56686. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  56687. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  56688. //
  56689. // Then the mip angle used to genreate the next level of the mip chain from the first level
  56690. // is a_InitialMipAngle
  56691. //
  56692. // The angle for the subsequent levels of the mip chain are specified by their parents
  56693. // filtering angle and a per-level scale and bias
  56694. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  56695. //
  56696. //--------------------------------------------------------------------------------------
  56697. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  56698. // First, take count of the lighting model to modify SpecularPower
  56699. // 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;
  56700. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  56701. //Cone angle start (for generating subsequent mip levels)
  56702. var currentSpecularPower = this.specularPower;
  56703. //Build filter lookup tables based on the source miplevel size
  56704. this.precomputeFilterLookupTables(this.inputSize);
  56705. // Note that we need to filter the first level before generating mipmap
  56706. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  56707. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  56708. // TODO : Write a function to copy and scale the base mipmap in output
  56709. // I am just lazy here and just put a high specular power value, and do some if.
  56710. if (this.excludeBase && (levelIndex == 0)) {
  56711. // 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).
  56712. currentSpecularPower = 100000.0;
  56713. }
  56714. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  56715. var srcCubeImage = this.input;
  56716. var dstCubeImage = this._outputSurface[levelIndex];
  56717. var dstSize = this.outputSize >> levelIndex;
  56718. // Compute required angle.
  56719. var angle = this.getBaseFilterAngle(currentSpecularPower);
  56720. // filter cube surfaces
  56721. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  56722. // fix seams
  56723. if (this.fixup) {
  56724. this.fixupCubeEdges(dstCubeImage, dstSize);
  56725. }
  56726. // Decrease the specular power to generate the mipmap chain
  56727. // TODO : Use another method for Exclude (see first comment at start of the function
  56728. if (this.excludeBase && (levelIndex == 0)) {
  56729. currentSpecularPower = this.specularPower;
  56730. }
  56731. currentSpecularPower *= this.cosinePowerDropPerMip;
  56732. }
  56733. };
  56734. //--------------------------------------------------------------------------------------
  56735. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  56736. // It allow to optimize the texel to access base on the specular power.
  56737. //--------------------------------------------------------------------------------------
  56738. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  56739. // We want to find the alpha such that:
  56740. // cos(alpha)^cosinePower = epsilon
  56741. // That's: acos(epsilon^(1/cosinePower))
  56742. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  56743. var angle = 180.0;
  56744. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  56745. angle *= 180.0 / Math.PI; // Convert to degree
  56746. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  56747. return angle;
  56748. };
  56749. //--------------------------------------------------------------------------------------
  56750. //Builds the following lookup tables prior to filtering:
  56751. // -normalizer cube map
  56752. // -tap weight lookup table
  56753. //
  56754. //--------------------------------------------------------------------------------------
  56755. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  56756. var srcTexelAngle;
  56757. var iCubeFace;
  56758. //clear pre-existing normalizer cube map
  56759. this._normCubeMap = [];
  56760. //Normalized vectors per cubeface and per-texel solid angle
  56761. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  56762. };
  56763. //--------------------------------------------------------------------------------------
  56764. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  56765. //
  56766. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  56767. //
  56768. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  56769. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  56770. // below
  56771. //--------------------------------------------------------------------------------------
  56772. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  56773. var iCubeFace;
  56774. var u;
  56775. var v;
  56776. //iterate over cube faces
  56777. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  56778. //First three channels for norm cube, and last channel for solid angle
  56779. this._normCubeMap.push(new Float32Array(size * size * 4));
  56780. //fast texture walk, build normalizer cube map
  56781. var facesData = this.input[iCubeFace];
  56782. for (v = 0; v < size; v++) {
  56783. for (u = 0; u < size; u++) {
  56784. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  56785. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  56786. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  56787. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  56788. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  56789. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  56790. }
  56791. }
  56792. }
  56793. };
  56794. //--------------------------------------------------------------------------------------
  56795. // Convert cubemap face texel coordinates and face idx to 3D vector
  56796. // note the U and V coords are integer coords and range from 0 to size-1
  56797. // this routine can be used to generate a normalizer cube map
  56798. //--------------------------------------------------------------------------------------
  56799. // SL BEGIN
  56800. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  56801. var nvcU;
  56802. var nvcV;
  56803. var tempVec;
  56804. // Change from original AMD code
  56805. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  56806. // + 0.5f is for texel center addressing
  56807. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  56808. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  56809. // warp fixup
  56810. if (fixup && size > 1) {
  56811. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  56812. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  56813. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  56814. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  56815. }
  56816. // Get current vector
  56817. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  56818. // U contribution
  56819. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  56820. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  56821. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  56822. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  56823. // V contribution and Sum
  56824. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  56825. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  56826. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  56827. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  56828. //add face axis
  56829. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  56830. PMREMGenerator._vectorTemp.x += faceAxis[0];
  56831. PMREMGenerator._vectorTemp.y += faceAxis[1];
  56832. PMREMGenerator._vectorTemp.z += faceAxis[2];
  56833. //normalize vector
  56834. PMREMGenerator._vectorTemp.normalize();
  56835. return PMREMGenerator._vectorTemp;
  56836. };
  56837. //--------------------------------------------------------------------------------------
  56838. // Convert 3D vector to cubemap face texel coordinates and face idx
  56839. // note the U and V coords are integer coords and range from 0 to size-1
  56840. // this routine can be used to generate a normalizer cube map
  56841. //
  56842. // returns face IDX and texel coords
  56843. //--------------------------------------------------------------------------------------
  56844. // SL BEGIN
  56845. /*
  56846. Mapping Texture Coordinates to Cube Map Faces
  56847. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  56848. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  56849. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  56850. map arrangement in Pixar's RenderMan package.
  56851. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  56852. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  56853. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  56854. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  56855. the major axis direction). The target column in the table below explains how the major axis direction
  56856. maps to the 2D image of a particular cube map target.
  56857. major axis
  56858. direction target sc tc ma
  56859. ---------- --------------------------------- --- --- ---
  56860. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  56861. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  56862. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  56863. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  56864. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  56865. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  56866. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  56867. an updated (s,t) is calculated as follows
  56868. s = ( sc/|ma| + 1 ) / 2
  56869. t = ( tc/|ma| + 1 ) / 2
  56870. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  56871. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  56872. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  56873. */
  56874. // Note this method return U and V in range from 0 to size-1
  56875. // SL END
  56876. // Store the information in vector3 for convenience (faceindex, u, v)
  56877. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  56878. var maxCoord;
  56879. var faceIdx;
  56880. //absolute value 3
  56881. var absX = Math.abs(x);
  56882. var absY = Math.abs(y);
  56883. var absZ = Math.abs(z);
  56884. if (absX >= absY && absX >= absZ) {
  56885. maxCoord = absX;
  56886. if (x >= 0) {
  56887. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  56888. }
  56889. else {
  56890. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  56891. }
  56892. }
  56893. else if (absY >= absX && absY >= absZ) {
  56894. maxCoord = absY;
  56895. if (y >= 0) {
  56896. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  56897. }
  56898. else {
  56899. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  56900. }
  56901. }
  56902. else {
  56903. maxCoord = absZ;
  56904. if (z >= 0) {
  56905. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  56906. }
  56907. else {
  56908. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  56909. }
  56910. }
  56911. //divide through by max coord so face vector lies on cube face
  56912. var scale = 1 / maxCoord;
  56913. x *= scale;
  56914. y *= scale;
  56915. z *= scale;
  56916. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  56917. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  56918. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  56919. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  56920. // Modify original AMD code to return value from 0 to Size - 1
  56921. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  56922. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  56923. PMREMGenerator._vectorTemp.x = faceIdx;
  56924. PMREMGenerator._vectorTemp.y = u;
  56925. PMREMGenerator._vectorTemp.z = v;
  56926. return PMREMGenerator._vectorTemp;
  56927. };
  56928. //--------------------------------------------------------------------------------------
  56929. //Original code from Ignacio CastaÒo
  56930. // This formula is from Manne ÷hrstrˆm's thesis.
  56931. // Take two coordiantes in the range [-1, 1] that define a portion of a
  56932. // cube face and return the area of the projection of that portion on the
  56933. // surface of the sphere.
  56934. //--------------------------------------------------------------------------------------
  56935. PMREMGenerator.prototype.areaElement = function (x, y) {
  56936. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  56937. };
  56938. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  56939. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  56940. // (+ 0.5f is for texel center addressing)
  56941. u = (2.0 * (u + 0.5) / size) - 1.0;
  56942. v = (2.0 * (v + 0.5) / size) - 1.0;
  56943. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  56944. var invResolution = 1.0 / size;
  56945. // U and V are the -1..1 texture coordinate on the current face.
  56946. // Get projected area for this texel
  56947. var x0 = u - invResolution;
  56948. var y0 = v - invResolution;
  56949. var x1 = u + invResolution;
  56950. var y1 = v + invResolution;
  56951. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  56952. return solidAngle;
  56953. };
  56954. //--------------------------------------------------------------------------------------
  56955. //The key to the speed of these filtering routines is to quickly define a per-face
  56956. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  56957. // Later these pixels are selectively processed based on their dot products to see if
  56958. // they reside within the filtering cone.
  56959. //
  56960. //This is done by computing the smallest per-texel angle to get a conservative estimate
  56961. // of the number of texels needed to be covered in width and height order to filter the
  56962. // region. the bounding box for the center taps face is defined first, and if the
  56963. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  56964. // defined next
  56965. //--------------------------------------------------------------------------------------
  56966. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  56967. // note that pixels within these regions may be rejected
  56968. // based on the anlge
  56969. var iCubeFace;
  56970. var u;
  56971. var v;
  56972. // bounding box per face to specify region to process
  56973. var filterExtents = [];
  56974. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  56975. filterExtents.push(new CMGBoundinBox());
  56976. }
  56977. // min angle a src texel can cover (in degrees)
  56978. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  56979. // angle about center tap to define filter cone
  56980. // filter angle is 1/2 the cone angle
  56981. var filterAngle = filterConeAngle / 2.0;
  56982. //ensure filter angle is larger than a texel
  56983. if (filterAngle < srcTexelAngle) {
  56984. filterAngle = srcTexelAngle;
  56985. }
  56986. //ensure filter cone is always smaller than the hemisphere
  56987. if (filterAngle > 90.0) {
  56988. filterAngle = 90.0;
  56989. }
  56990. // the maximum number of texels in 1D the filter cone angle will cover
  56991. // used to determine bounding box size for filter extents
  56992. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  56993. // ensure conservative region always covers at least one texel
  56994. if (filterSize < 1) {
  56995. filterSize = 1;
  56996. }
  56997. // dotProdThresh threshold based on cone angle to determine whether or not taps
  56998. // reside within the cone angle
  56999. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  57000. // process required faces
  57001. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  57002. //iterate over dst cube map face texel
  57003. for (v = 0; v < dstSize; v++) {
  57004. for (u = 0; u < dstSize; u++) {
  57005. //get center tap direction
  57006. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  57007. //clear old per-face filter extents
  57008. this.clearFilterExtents(filterExtents);
  57009. //define per-face filter extents
  57010. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  57011. //perform filtering of src faces using filter extents
  57012. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  57013. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  57014. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  57015. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  57016. }
  57017. }
  57018. }
  57019. };
  57020. //--------------------------------------------------------------------------------------
  57021. //Clear filter extents for the 6 cube map faces
  57022. //--------------------------------------------------------------------------------------
  57023. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  57024. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  57025. filterExtents[iCubeFaces].clear();
  57026. }
  57027. };
  57028. //--------------------------------------------------------------------------------------
  57029. //Define per-face bounding box filter extents
  57030. //
  57031. // These define conservative texel regions in each of the faces the filter can possibly
  57032. // process. When the pixels in the regions are actually processed, the dot product
  57033. // between the tap vector and the center tap vector is used to determine the weight of
  57034. // the tap and whether or not the tap is within the cone.
  57035. //
  57036. //--------------------------------------------------------------------------------------
  57037. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  57038. //neighboring face and bleed over amount, and width of BBOX for
  57039. // left, right, top, and bottom edges of this face
  57040. var bleedOverAmount = [0, 0, 0, 0];
  57041. var bleedOverBBoxMin = [0, 0, 0, 0];
  57042. var bleedOverBBoxMax = [0, 0, 0, 0];
  57043. var neighborFace;
  57044. var neighborEdge;
  57045. var oppositeFaceIdx;
  57046. //get face idx, and u, v info from center tap dir
  57047. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  57048. var faceIdx = result.x;
  57049. var u = result.y;
  57050. var v = result.z;
  57051. //define bbox size within face
  57052. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  57053. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  57054. filterExtents[faceIdx].clampMin(0, 0, 0);
  57055. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  57056. //u and v extent in face corresponding to center tap
  57057. var minU = filterExtents[faceIdx].min.x;
  57058. var minV = filterExtents[faceIdx].min.y;
  57059. var maxU = filterExtents[faceIdx].max.x;
  57060. var maxV = filterExtents[faceIdx].max.y;
  57061. //bleed over amounts for face across u=0 edge (left)
  57062. bleedOverAmount[0] = (bboxSize - u);
  57063. bleedOverBBoxMin[0] = minV;
  57064. bleedOverBBoxMax[0] = maxV;
  57065. //bleed over amounts for face across u=1 edge (right)
  57066. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  57067. bleedOverBBoxMin[1] = minV;
  57068. bleedOverBBoxMax[1] = maxV;
  57069. //bleed over to face across v=0 edge (up)
  57070. bleedOverAmount[2] = (bboxSize - v);
  57071. bleedOverBBoxMin[2] = minU;
  57072. bleedOverBBoxMax[2] = maxU;
  57073. //bleed over to face across v=1 edge (down)
  57074. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  57075. bleedOverBBoxMin[3] = minU;
  57076. bleedOverBBoxMax[3] = maxU;
  57077. //compute bleed over regions in neighboring faces
  57078. for (var i = 0; i < 4; i++) {
  57079. if (bleedOverAmount[i] > 0) {
  57080. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  57081. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  57082. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  57083. // be flipped: the cases are
  57084. // if a left edge mates with a left or bottom edge on the neighbor
  57085. // if a top edge mates with a top or right edge on the neighbor
  57086. // if a right edge mates with a right or top edge on the neighbor
  57087. // if a bottom edge mates with a bottom or left edge on the neighbor
  57088. //Seeing as the edges are enumerated as follows
  57089. // left =0
  57090. // right =1
  57091. // top =2
  57092. // bottom =3
  57093. //
  57094. // so if the edge enums are the same, or the sum of the enums == 3,
  57095. // the bbox needs to be flipped
  57096. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  57097. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  57098. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  57099. }
  57100. //The way the bounding box is extended onto the neighboring face
  57101. // depends on which edge of neighboring face abuts with this one
  57102. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  57103. case PMREMGenerator.CP_EDGE_LEFT:
  57104. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  57105. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  57106. break;
  57107. case PMREMGenerator.CP_EDGE_RIGHT:
  57108. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  57109. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  57110. break;
  57111. case PMREMGenerator.CP_EDGE_TOP:
  57112. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  57113. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  57114. break;
  57115. case PMREMGenerator.CP_EDGE_BOTTOM:
  57116. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  57117. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  57118. break;
  57119. }
  57120. //clamp filter extents in non-center tap faces to remain within surface
  57121. filterExtents[neighborFace].clampMin(0, 0, 0);
  57122. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  57123. }
  57124. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  57125. // from the center tap face, then process the opposite face entirely for now.
  57126. //Note that the cases in which this happens, what usually happens is that
  57127. // more than one edge bleeds onto the opposite face, and the bounding box
  57128. // encompasses the entire cube map face.
  57129. if (bleedOverAmount[i] > srcSize) {
  57130. //determine opposite face
  57131. switch (faceIdx) {
  57132. case PMREMGenerator.CP_FACE_X_POS:
  57133. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  57134. break;
  57135. case PMREMGenerator.CP_FACE_X_NEG:
  57136. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  57137. break;
  57138. case PMREMGenerator.CP_FACE_Y_POS:
  57139. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  57140. break;
  57141. case PMREMGenerator.CP_FACE_Y_NEG:
  57142. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  57143. break;
  57144. case PMREMGenerator.CP_FACE_Z_POS:
  57145. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  57146. break;
  57147. case PMREMGenerator.CP_FACE_Z_NEG:
  57148. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  57149. break;
  57150. default:
  57151. break;
  57152. }
  57153. //just encompass entire face for now
  57154. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  57155. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  57156. }
  57157. }
  57158. };
  57159. //--------------------------------------------------------------------------------------
  57160. //ProcessFilterExtents
  57161. // Process bounding box in each cube face
  57162. //
  57163. //--------------------------------------------------------------------------------------
  57164. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  57165. //accumulators are 64-bit floats in order to have the precision needed
  57166. // over a summation of a large number of pixels
  57167. var dstAccum = [0, 0, 0, 0];
  57168. var weightAccum = 0;
  57169. var k = 0;
  57170. var nSrcChannels = this.numChannels;
  57171. // norm cube map and srcCubeMap have same face width
  57172. var faceWidth = srcSize;
  57173. //amount to add to pointer to move to next scanline in images
  57174. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  57175. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  57176. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  57177. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  57178. // iterate over cubefaces
  57179. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  57180. //if bbox is non empty
  57181. if (!filterExtents[iFaceIdx].empty()) {
  57182. var uStart = filterExtents[iFaceIdx].min.x;
  57183. var vStart = filterExtents[iFaceIdx].min.y;
  57184. var uEnd = filterExtents[iFaceIdx].max.x;
  57185. var vEnd = filterExtents[iFaceIdx].max.y;
  57186. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  57187. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  57188. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  57189. for (var v = vStart; v <= vEnd; v++) {
  57190. var normCubeRowWalk = 0;
  57191. var srcCubeRowWalk = 0;
  57192. for (var u = uStart; u <= uEnd; u++) {
  57193. //pointer to direction in cube map associated with texel
  57194. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  57195. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  57196. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  57197. //check dot product to see if texel is within cone
  57198. var tapDotProd = texelVectX * centerTapDir.x +
  57199. texelVectY * centerTapDir.y +
  57200. texelVectZ * centerTapDir.z;
  57201. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  57202. //solid angle stored in 4th channel of normalizer/solid angle cube map
  57203. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  57204. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  57205. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  57206. // so just adding one to specularpower do the trick.
  57207. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  57208. //iterate over channels
  57209. for (k = 0; k < nSrcChannels; k++) {
  57210. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  57211. srcCubeRowWalk++;
  57212. }
  57213. weightAccum += weight; //accumulate weight
  57214. }
  57215. else {
  57216. //step across source pixel
  57217. srcCubeRowWalk += nSrcChannels;
  57218. }
  57219. normCubeRowWalk += 4; // 4 channels per norm cube map.
  57220. }
  57221. startIndexNormCubeMap += normCubePitch;
  57222. startIndexSrcCubeMap += srcCubePitch;
  57223. }
  57224. }
  57225. }
  57226. //divide through by weights if weight is non zero
  57227. if (weightAccum != 0.0) {
  57228. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  57229. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  57230. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  57231. if (this.numChannels > 3) {
  57232. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  57233. }
  57234. }
  57235. else {
  57236. // otherwise sample nearest
  57237. // get face idx and u, v texel coordinate in face
  57238. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  57239. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  57240. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  57241. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  57242. if (this.numChannels > 3) {
  57243. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  57244. }
  57245. }
  57246. return PMREMGenerator._vectorTemp;
  57247. };
  57248. //--------------------------------------------------------------------------------------
  57249. // Fixup cube edges
  57250. //
  57251. // average texels on cube map faces across the edges
  57252. // WARP/BENT Method Only.
  57253. //--------------------------------------------------------------------------------------
  57254. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  57255. var k;
  57256. var j;
  57257. var i;
  57258. var iFace;
  57259. var iCorner = 0;
  57260. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  57261. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  57262. // note that if functionality to filter across the three texels for each corner, then
  57263. //indexed by corner and face idx. the array contains the face the start points belongs to.
  57264. var cornerPtr = [
  57265. [[], [], []],
  57266. [[], [], []],
  57267. [[], [], []],
  57268. [[], [], []],
  57269. [[], [], []],
  57270. [[], [], []],
  57271. [[], [], []],
  57272. [[], [], []]
  57273. ];
  57274. //if there is no fixup, or fixup width = 0, do nothing
  57275. if (cubeMapSize < 1) {
  57276. return;
  57277. }
  57278. //special case 1x1 cubemap, average face colors
  57279. if (cubeMapSize == 1) {
  57280. //iterate over channels
  57281. for (k = 0; k < this.numChannels; k++) {
  57282. var accum = 0.0;
  57283. //iterate over faces to accumulate face colors
  57284. for (iFace = 0; iFace < 6; iFace++) {
  57285. accum += cubeMap[iFace][k];
  57286. }
  57287. //compute average over 6 face colors
  57288. accum /= 6.0;
  57289. //iterate over faces to distribute face colors
  57290. for (iFace = 0; iFace < 6; iFace++) {
  57291. cubeMap[iFace][k] = accum;
  57292. }
  57293. }
  57294. return;
  57295. }
  57296. //iterate over faces to collect list of corner texel pointers
  57297. for (iFace = 0; iFace < 6; iFace++) {
  57298. //the 4 corner pointers for this face
  57299. faceCornerStartIndicies[0] = [iFace, 0];
  57300. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  57301. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  57302. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  57303. //iterate over face corners to collect cube corner pointers
  57304. for (iCorner = 0; iCorner < 4; iCorner++) {
  57305. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  57306. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  57307. cornerNumPtrs[corner]++;
  57308. }
  57309. }
  57310. //iterate over corners to average across corner tap values
  57311. for (iCorner = 0; iCorner < 8; iCorner++) {
  57312. for (k = 0; k < this.numChannels; k++) {
  57313. var cornerTapAccum = 0.0;
  57314. //iterate over corner texels and average results
  57315. for (i = 0; i < 3; i++) {
  57316. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  57317. }
  57318. //divide by 3 to compute average of corner tap values
  57319. cornerTapAccum *= (1.0 / 3.0);
  57320. //iterate over corner texels and average results
  57321. for (i = 0; i < 3; i++) {
  57322. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  57323. }
  57324. }
  57325. }
  57326. //iterate over the twelve edges of the cube to average across edges
  57327. for (i = 0; i < 12; i++) {
  57328. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  57329. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  57330. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  57331. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  57332. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  57333. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  57334. var edgeWalk = 0;
  57335. var neighborEdgeWalk = 0;
  57336. //Determine walking pointers based on edge type
  57337. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  57338. switch (edge) {
  57339. case PMREMGenerator.CP_EDGE_LEFT:
  57340. // no change to faceEdgeStartPtr
  57341. edgeWalk = this.numChannels * cubeMapSize;
  57342. break;
  57343. case PMREMGenerator.CP_EDGE_RIGHT:
  57344. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57345. edgeWalk = this.numChannels * cubeMapSize;
  57346. break;
  57347. case PMREMGenerator.CP_EDGE_TOP:
  57348. // no change to faceEdgeStartPtr
  57349. edgeWalk = this.numChannels;
  57350. break;
  57351. case PMREMGenerator.CP_EDGE_BOTTOM:
  57352. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  57353. edgeWalk = this.numChannels;
  57354. break;
  57355. }
  57356. //For certain types of edge abutments, the neighbor edge walk needs to
  57357. // be flipped: the cases are
  57358. // if a left edge mates with a left or bottom edge on the neighbor
  57359. // if a top edge mates with a top or right edge on the neighbor
  57360. // if a right edge mates with a right or top edge on the neighbor
  57361. // if a bottom edge mates with a bottom or left edge on the neighbor
  57362. //Seeing as the edges are enumerated as follows
  57363. // left =0
  57364. // right =1
  57365. // top =2
  57366. // bottom =3
  57367. //
  57368. //If the edge enums are the same, or the sum of the enums == 3,
  57369. // the neighbor edge walk needs to be flipped
  57370. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  57371. switch (neighborEdge) {
  57372. case PMREMGenerator.CP_EDGE_LEFT:
  57373. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  57374. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  57375. break;
  57376. case PMREMGenerator.CP_EDGE_RIGHT:
  57377. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  57378. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  57379. break;
  57380. case PMREMGenerator.CP_EDGE_TOP:
  57381. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57382. neighborEdgeWalk = -this.numChannels;
  57383. break;
  57384. case PMREMGenerator.CP_EDGE_BOTTOM:
  57385. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  57386. neighborEdgeWalk = -this.numChannels;
  57387. break;
  57388. }
  57389. }
  57390. else {
  57391. //swapped direction neighbor edge walk
  57392. switch (neighborEdge) {
  57393. case PMREMGenerator.CP_EDGE_LEFT:
  57394. //no change to neighborEdgeStartPtr for this case since it points
  57395. // to the upper left corner already
  57396. neighborEdgeWalk = this.numChannels * cubeMapSize;
  57397. break;
  57398. case PMREMGenerator.CP_EDGE_RIGHT:
  57399. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57400. neighborEdgeWalk = this.numChannels * cubeMapSize;
  57401. break;
  57402. case PMREMGenerator.CP_EDGE_TOP:
  57403. //no change to neighborEdgeStartPtr for this case since it points
  57404. // to the upper left corner already
  57405. neighborEdgeWalk = this.numChannels;
  57406. break;
  57407. case PMREMGenerator.CP_EDGE_BOTTOM:
  57408. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  57409. neighborEdgeWalk = this.numChannels;
  57410. break;
  57411. }
  57412. }
  57413. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  57414. //nearby neighborhood
  57415. //step ahead one texel on edge
  57416. edgeStartIndex += edgeWalk;
  57417. neighborEdgeStartIndex += neighborEdgeWalk;
  57418. // note that this loop does not process the corner texels, since they have already been
  57419. // averaged across faces across earlier
  57420. for (j = 1; j < (cubeMapSize - 1); j++) {
  57421. //for each set of taps along edge, average them
  57422. // and rewrite the results into the edges
  57423. for (k = 0; k < this.numChannels; k++) {
  57424. var edgeTap = cubeMap[face][edgeStartIndex + k];
  57425. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  57426. //compute average of tap intensity values
  57427. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  57428. //propagate average of taps to edge taps
  57429. cubeMap[face][edgeStartIndex + k] = avgTap;
  57430. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  57431. }
  57432. edgeStartIndex += edgeWalk;
  57433. neighborEdgeStartIndex += neighborEdgeWalk;
  57434. }
  57435. }
  57436. };
  57437. return PMREMGenerator;
  57438. }());
  57439. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  57440. PMREMGenerator.CP_UDIR = 0;
  57441. PMREMGenerator.CP_VDIR = 1;
  57442. PMREMGenerator.CP_FACEAXIS = 2;
  57443. //used to index cube faces
  57444. PMREMGenerator.CP_FACE_X_POS = 0;
  57445. PMREMGenerator.CP_FACE_X_NEG = 1;
  57446. PMREMGenerator.CP_FACE_Y_POS = 2;
  57447. PMREMGenerator.CP_FACE_Y_NEG = 3;
  57448. PMREMGenerator.CP_FACE_Z_POS = 4;
  57449. PMREMGenerator.CP_FACE_Z_NEG = 5;
  57450. //used to index image edges
  57451. // NOTE.. the actual number corresponding to the edge is important
  57452. // do not change these, or the code will break
  57453. //
  57454. // CP_EDGE_LEFT is u = 0
  57455. // CP_EDGE_RIGHT is u = width-1
  57456. // CP_EDGE_TOP is v = 0
  57457. // CP_EDGE_BOTTOM is v = height-1
  57458. PMREMGenerator.CP_EDGE_LEFT = 0;
  57459. PMREMGenerator.CP_EDGE_RIGHT = 1;
  57460. PMREMGenerator.CP_EDGE_TOP = 2;
  57461. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  57462. //corners of CUBE map (P or N specifys if it corresponds to the
  57463. // positive or negative direction each of X, Y, and Z
  57464. PMREMGenerator.CP_CORNER_NNN = 0;
  57465. PMREMGenerator.CP_CORNER_NNP = 1;
  57466. PMREMGenerator.CP_CORNER_NPN = 2;
  57467. PMREMGenerator.CP_CORNER_NPP = 3;
  57468. PMREMGenerator.CP_CORNER_PNN = 4;
  57469. PMREMGenerator.CP_CORNER_PNP = 5;
  57470. PMREMGenerator.CP_CORNER_PPN = 6;
  57471. PMREMGenerator.CP_CORNER_PPP = 7;
  57472. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  57473. //3x2 matrices that map cube map indexing vectors in 3d
  57474. // (after face selection and divide through by the
  57475. // _ABSOLUTE VALUE_ of the max coord)
  57476. // into NVC space
  57477. //Note this currently assumes the D3D cube face ordering and orientation
  57478. PMREMGenerator._sgFace2DMapping = [
  57479. //XPOS face
  57480. [[0, 0, -1],
  57481. [0, -1, 0],
  57482. [1, 0, 0]],
  57483. //XNEG face
  57484. [[0, 0, 1],
  57485. [0, -1, 0],
  57486. [-1, 0, 0]],
  57487. //YPOS face
  57488. [[1, 0, 0],
  57489. [0, 0, 1],
  57490. [0, 1, 0]],
  57491. //YNEG face
  57492. [[1, 0, 0],
  57493. [0, 0, -1],
  57494. [0, -1, 0]],
  57495. //ZPOS face
  57496. [[1, 0, 0],
  57497. [0, -1, 0],
  57498. [0, 0, 1]],
  57499. //ZNEG face
  57500. [[-1, 0, 0],
  57501. [0, -1, 0],
  57502. [0, 0, -1]],
  57503. ];
  57504. //------------------------------------------------------------------------------
  57505. // D3D cube map face specification
  57506. // mapping from 3D x,y,z cube map lookup coordinates
  57507. // to 2D within face u,v coordinates
  57508. //
  57509. // --------------------> U direction
  57510. // | (within-face texture space)
  57511. // | _____
  57512. // | | |
  57513. // | | +Y |
  57514. // | _____|_____|_____ _____
  57515. // | | | | | |
  57516. // | | -X | +Z | +X | -Z |
  57517. // | |_____|_____|_____|_____|
  57518. // | | |
  57519. // | | -Y |
  57520. // | |_____|
  57521. // |
  57522. // v V direction
  57523. // (within-face texture space)
  57524. //------------------------------------------------------------------------------
  57525. //Information about neighbors and how texture coorrdinates change across faces
  57526. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  57527. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  57528. //Note this currently assumes the D3D cube face ordering and orientation
  57529. PMREMGenerator._sgCubeNgh = [
  57530. //XPOS face
  57531. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57532. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  57533. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57534. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  57535. //XNEG face
  57536. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  57537. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  57538. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  57539. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  57540. //YPOS face
  57541. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  57542. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  57543. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  57544. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  57545. //YNEG face
  57546. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  57547. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57548. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57549. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  57550. //ZPOS face
  57551. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  57552. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  57553. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57554. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  57555. //ZNEG face
  57556. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57557. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  57558. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  57559. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  57560. ];
  57561. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  57562. // this table is used to average over the edges.
  57563. PMREMGenerator._sgCubeEdgeList = [
  57564. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  57565. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57566. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  57567. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57568. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  57569. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  57570. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  57571. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  57572. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  57573. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57574. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  57575. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  57576. ];
  57577. //Information about which of the 8 cube corners are correspond to the
  57578. // the 4 corners in each cube face
  57579. // the order is upper left, upper right, lower left, lower right
  57580. PMREMGenerator._sgCubeCornerList = [
  57581. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  57582. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  57583. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  57584. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  57585. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  57586. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  57587. ];
  57588. Internals.PMREMGenerator = PMREMGenerator;
  57589. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57590. })(BABYLON || (BABYLON = {}));
  57591. //# sourceMappingURL=babylon.tools.pmremGenerator.js.map
  57592. var BABYLON;
  57593. (function (BABYLON) {
  57594. /**
  57595. * This represents a texture coming from an HDR input.
  57596. *
  57597. * The only supported format is currently panorama picture stored in RGBE format.
  57598. * Example of such files can be found on HDRLib: http://hdrlib.com/
  57599. */
  57600. var HDRCubeTexture = (function (_super) {
  57601. __extends(HDRCubeTexture, _super);
  57602. /**
  57603. * Instantiates an HDRTexture from the following parameters.
  57604. *
  57605. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  57606. * @param scene The scene the texture will be used in
  57607. * @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.
  57608. * @param noMipmap Forces to not generate the mipmap if true
  57609. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  57610. * @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)
  57611. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  57612. */
  57613. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  57614. if (noMipmap === void 0) { noMipmap = false; }
  57615. if (generateHarmonics === void 0) { generateHarmonics = true; }
  57616. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  57617. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  57618. if (onLoad === void 0) { onLoad = null; }
  57619. if (onError === void 0) { onError = null; }
  57620. var _this = _super.call(this, scene) || this;
  57621. _this._useInGammaSpace = false;
  57622. _this._generateHarmonics = true;
  57623. _this._isBABYLONPreprocessed = false;
  57624. _this._onLoad = null;
  57625. _this._onError = null;
  57626. /**
  57627. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  57628. */
  57629. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57630. /**
  57631. * The spherical polynomial data extracted from the texture.
  57632. */
  57633. _this.sphericalPolynomial = null;
  57634. /**
  57635. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  57636. * This is usefull at run time to apply the good shader.
  57637. */
  57638. _this.isPMREM = false;
  57639. if (!url) {
  57640. return _this;
  57641. }
  57642. _this.name = url;
  57643. _this.url = url;
  57644. _this.hasAlpha = false;
  57645. _this.isCube = true;
  57646. _this._textureMatrix = BABYLON.Matrix.Identity();
  57647. _this._onLoad = onLoad;
  57648. _this._onError = onError;
  57649. if (size) {
  57650. _this._isBABYLONPreprocessed = false;
  57651. _this._noMipmap = noMipmap;
  57652. _this._size = size;
  57653. _this._useInGammaSpace = useInGammaSpace;
  57654. _this._usePMREMGenerator = usePMREMGenerator &&
  57655. scene.getEngine().getCaps().textureLOD &&
  57656. _this.getScene().getEngine().getCaps().textureFloat &&
  57657. !_this._useInGammaSpace;
  57658. }
  57659. else {
  57660. _this._isBABYLONPreprocessed = true;
  57661. _this._noMipmap = false;
  57662. _this._useInGammaSpace = false;
  57663. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  57664. _this.getScene().getEngine().getCaps().textureFloat &&
  57665. !_this._useInGammaSpace;
  57666. }
  57667. _this.isPMREM = _this._usePMREMGenerator;
  57668. _this._texture = _this._getFromCache(url, _this._noMipmap);
  57669. if (!_this._texture) {
  57670. if (!scene.useDelayedTextureLoading) {
  57671. _this.loadTexture();
  57672. }
  57673. else {
  57674. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57675. }
  57676. }
  57677. return _this;
  57678. }
  57679. /**
  57680. * Occurs when the file is a preprocessed .babylon.hdr file.
  57681. */
  57682. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  57683. var _this = this;
  57684. var mipLevels = 0;
  57685. var floatArrayView = null;
  57686. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  57687. var mips = [];
  57688. var startIndex = 30;
  57689. for (var level = 0; level < mipLevels; level++) {
  57690. mips.push([]);
  57691. // Fill each pixel of the mip level.
  57692. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  57693. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57694. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  57695. mips[level].push(faceData);
  57696. startIndex += faceSize;
  57697. }
  57698. }
  57699. return mips;
  57700. } : null;
  57701. var callback = function (buffer) {
  57702. // Create Native Array Views
  57703. var intArrayView = new Int32Array(buffer);
  57704. floatArrayView = new Float32Array(buffer);
  57705. // Fill header.
  57706. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  57707. _this._size = intArrayView[1]; // CubeMap max mip face size.
  57708. // Update Texture Information.
  57709. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  57710. // Fill polynomial information.
  57711. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  57712. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  57713. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  57714. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  57715. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  57716. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  57717. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  57718. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  57719. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  57720. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  57721. // Fill pixel data.
  57722. mipLevels = intArrayView[29]; // Number of mip levels.
  57723. var startIndex = 30;
  57724. var data = [];
  57725. var faceSize = Math.pow(_this._size, 2) * 3;
  57726. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57727. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  57728. startIndex += faceSize;
  57729. }
  57730. var results = [];
  57731. var byteArray = null;
  57732. // Push each faces.
  57733. for (var k = 0; k < 6; k++) {
  57734. var dataFace = null;
  57735. // If special cases.
  57736. if (!mipmapGenerator) {
  57737. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  57738. dataFace = data[j];
  57739. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  57740. // 3 channels of 1 bytes per pixel in bytes.
  57741. var byteBuffer = new ArrayBuffer(faceSize);
  57742. byteArray = new Uint8Array(byteBuffer);
  57743. }
  57744. for (var i = 0; i < _this._size * _this._size; i++) {
  57745. // Put in gamma space if requested.
  57746. if (_this._useInGammaSpace) {
  57747. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  57748. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  57749. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  57750. }
  57751. // Convert to int texture for fallback.
  57752. if (byteArray) {
  57753. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  57754. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  57755. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  57756. // May use luminance instead if the result is not accurate.
  57757. var max = Math.max(Math.max(r, g), b);
  57758. if (max > 255) {
  57759. var scale = 255 / max;
  57760. r *= scale;
  57761. g *= scale;
  57762. b *= scale;
  57763. }
  57764. byteArray[(i * 3) + 0] = r;
  57765. byteArray[(i * 3) + 1] = g;
  57766. byteArray[(i * 3) + 2] = b;
  57767. }
  57768. }
  57769. }
  57770. else {
  57771. dataFace = data[k];
  57772. }
  57773. // Fill the array accordingly.
  57774. if (byteArray) {
  57775. results.push(byteArray);
  57776. }
  57777. else {
  57778. results.push(dataFace);
  57779. }
  57780. }
  57781. return results;
  57782. };
  57783. 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);
  57784. };
  57785. /**
  57786. * Occurs when the file is raw .hdr file.
  57787. */
  57788. HDRCubeTexture.prototype.loadHDRTexture = function () {
  57789. var _this = this;
  57790. var callback = function (buffer) {
  57791. // Extract the raw linear data.
  57792. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  57793. // Generate harmonics if needed.
  57794. if (_this._generateHarmonics) {
  57795. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  57796. }
  57797. var results = [];
  57798. var byteArray = null;
  57799. // Push each faces.
  57800. for (var j = 0; j < 6; j++) {
  57801. // Create uintarray fallback.
  57802. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  57803. // 3 channels of 1 bytes per pixel in bytes.
  57804. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  57805. byteArray = new Uint8Array(byteBuffer);
  57806. }
  57807. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  57808. // If special cases.
  57809. if (_this._useInGammaSpace || byteArray) {
  57810. for (var i = 0; i < _this._size * _this._size; i++) {
  57811. // Put in gamma space if requested.
  57812. if (_this._useInGammaSpace) {
  57813. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  57814. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  57815. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  57816. }
  57817. // Convert to int texture for fallback.
  57818. if (byteArray) {
  57819. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  57820. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  57821. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  57822. // May use luminance instead if the result is not accurate.
  57823. var max = Math.max(Math.max(r, g), b);
  57824. if (max > 255) {
  57825. var scale = 255 / max;
  57826. r *= scale;
  57827. g *= scale;
  57828. b *= scale;
  57829. }
  57830. byteArray[(i * 3) + 0] = r;
  57831. byteArray[(i * 3) + 1] = g;
  57832. byteArray[(i * 3) + 2] = b;
  57833. }
  57834. }
  57835. }
  57836. if (byteArray) {
  57837. results.push(byteArray);
  57838. }
  57839. else {
  57840. results.push(dataFace);
  57841. }
  57842. }
  57843. return results;
  57844. };
  57845. var mipmapGenerator = null;
  57846. if (!this._noMipmap &&
  57847. this._usePMREMGenerator) {
  57848. mipmapGenerator = function (data) {
  57849. // Custom setup of the generator matching with the PBR shader values.
  57850. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  57851. return generator.filterCubeMap();
  57852. };
  57853. }
  57854. 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);
  57855. };
  57856. /**
  57857. * Starts the loading process of the texture.
  57858. */
  57859. HDRCubeTexture.prototype.loadTexture = function () {
  57860. if (this._isBABYLONPreprocessed) {
  57861. this.loadBabylonTexture();
  57862. }
  57863. else {
  57864. this.loadHDRTexture();
  57865. }
  57866. };
  57867. HDRCubeTexture.prototype.clone = function () {
  57868. var size = this._isBABYLONPreprocessed ? null : this._size;
  57869. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  57870. // Base texture
  57871. newTexture.level = this.level;
  57872. newTexture.wrapU = this.wrapU;
  57873. newTexture.wrapV = this.wrapV;
  57874. newTexture.coordinatesIndex = this.coordinatesIndex;
  57875. newTexture.coordinatesMode = this.coordinatesMode;
  57876. return newTexture;
  57877. };
  57878. // Methods
  57879. HDRCubeTexture.prototype.delayLoad = function () {
  57880. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57881. return;
  57882. }
  57883. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57884. this._texture = this._getFromCache(this.url, this._noMipmap);
  57885. if (!this._texture) {
  57886. this.loadTexture();
  57887. }
  57888. };
  57889. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  57890. return this._textureMatrix;
  57891. };
  57892. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57893. var texture = null;
  57894. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  57895. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  57896. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  57897. texture.name = parsedTexture.name;
  57898. texture.hasAlpha = parsedTexture.hasAlpha;
  57899. texture.level = parsedTexture.level;
  57900. texture.coordinatesMode = parsedTexture.coordinatesMode;
  57901. }
  57902. return texture;
  57903. };
  57904. HDRCubeTexture.prototype.serialize = function () {
  57905. if (!this.name) {
  57906. return null;
  57907. }
  57908. var serializationObject = {};
  57909. serializationObject.name = this.name;
  57910. serializationObject.hasAlpha = this.hasAlpha;
  57911. serializationObject.isCube = true;
  57912. serializationObject.level = this.level;
  57913. serializationObject.size = this._size;
  57914. serializationObject.coordinatesMode = this.coordinatesMode;
  57915. serializationObject.useInGammaSpace = this._useInGammaSpace;
  57916. serializationObject.generateHarmonics = this._generateHarmonics;
  57917. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  57918. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  57919. serializationObject.customType = "BABYLON.HDRCubeTexture";
  57920. serializationObject.noMipmap = this._noMipmap;
  57921. return serializationObject;
  57922. };
  57923. /**
  57924. * Saves as a file the data contained in the texture in a binary format.
  57925. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  57926. * as the spherical used in the lighting.
  57927. * @param url The HDR file url.
  57928. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  57929. * @param onError Method called if any error happens during download.
  57930. * @return The packed binary data.
  57931. */
  57932. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  57933. if (onError === void 0) { onError = null; }
  57934. var callback = function (buffer) {
  57935. var data = new Blob([buffer], { type: 'application/octet-stream' });
  57936. // Returns a URL you can use as a href.
  57937. var objUrl = window.URL.createObjectURL(data);
  57938. // Simulates a link to it and click to dowload.
  57939. var a = document.createElement("a");
  57940. document.body.appendChild(a);
  57941. a.style.display = "none";
  57942. a.href = objUrl;
  57943. a.download = "envmap.babylon.hdr";
  57944. a.click();
  57945. };
  57946. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  57947. };
  57948. /**
  57949. * Serializes the data contained in the texture in a binary format.
  57950. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  57951. * as the spherical used in the lighting.
  57952. * @param url The HDR file url.
  57953. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  57954. * @param onError Method called if any error happens during download.
  57955. * @return The packed binary data.
  57956. */
  57957. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  57958. if (onError === void 0) { onError = null; }
  57959. // Needs the url tho create the texture.
  57960. if (!url) {
  57961. return null;
  57962. }
  57963. // Check Power of two size.
  57964. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  57965. return null;
  57966. }
  57967. var getDataCallback = function (dataBuffer) {
  57968. // Extract the raw linear data.
  57969. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  57970. // Generate harmonics if needed.
  57971. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  57972. // Generate seamless faces
  57973. var mipGeneratorArray = [];
  57974. // Data are known to be in +X +Y +Z -X -Y -Z
  57975. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  57976. mipGeneratorArray.push(cubeData.right); // +X
  57977. mipGeneratorArray.push(cubeData.left); // -X
  57978. mipGeneratorArray.push(cubeData.up); // +Y
  57979. mipGeneratorArray.push(cubeData.down); // -Y
  57980. mipGeneratorArray.push(cubeData.front); // +Z
  57981. mipGeneratorArray.push(cubeData.back); // -Z
  57982. // Custom setup of the generator matching with the PBR shader values.
  57983. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  57984. var mippedData = generator.filterCubeMap();
  57985. // Compute required byte length.
  57986. var byteLength = 1 * 4; // Raw Data Version int32.
  57987. byteLength += 4; // CubeMap max mip face size int32.
  57988. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  57989. // Add data size.
  57990. byteLength += 4; // Number of mip levels int32.
  57991. for (var level = 0; level < mippedData.length; level++) {
  57992. var mipSize = size >> level;
  57993. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  57994. }
  57995. // Prepare binary structure.
  57996. var buffer = new ArrayBuffer(byteLength);
  57997. var intArrayView = new Int32Array(buffer);
  57998. var floatArrayView = new Float32Array(buffer);
  57999. // Fill header.
  58000. intArrayView[0] = 1; // Version 1.
  58001. intArrayView[1] = size; // CubeMap max mip face size.
  58002. // Fill polynomial information.
  58003. sphericalPolynomial.x.toArray(floatArrayView, 2);
  58004. sphericalPolynomial.y.toArray(floatArrayView, 5);
  58005. sphericalPolynomial.z.toArray(floatArrayView, 8);
  58006. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  58007. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  58008. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  58009. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  58010. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  58011. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  58012. // Fill pixel data.
  58013. intArrayView[29] = mippedData.length; // Number of mip levels.
  58014. var startIndex = 30;
  58015. for (var level = 0; level < mippedData.length; level++) {
  58016. // Fill each pixel of the mip level.
  58017. var faceSize = Math.pow(size >> level, 2) * 3;
  58018. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58019. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  58020. startIndex += faceSize;
  58021. }
  58022. }
  58023. // Callback.
  58024. callback(buffer);
  58025. };
  58026. // Download and process.
  58027. BABYLON.Tools.LoadFile(url, function (data) {
  58028. getDataCallback(data);
  58029. }, null, null, true, onError);
  58030. };
  58031. return HDRCubeTexture;
  58032. }(BABYLON.BaseTexture));
  58033. HDRCubeTexture._facesMapping = [
  58034. "right",
  58035. "up",
  58036. "front",
  58037. "left",
  58038. "down",
  58039. "back"
  58040. ];
  58041. BABYLON.HDRCubeTexture = HDRCubeTexture;
  58042. })(BABYLON || (BABYLON = {}));
  58043. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  58044. var BABYLON;
  58045. (function (BABYLON) {
  58046. var Debug;
  58047. (function (Debug) {
  58048. /**
  58049. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  58050. */
  58051. var SkeletonViewer = (function () {
  58052. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  58053. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  58054. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  58055. this.skeleton = skeleton;
  58056. this.mesh = mesh;
  58057. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  58058. this.renderingGroupId = renderingGroupId;
  58059. this.color = BABYLON.Color3.White();
  58060. this._debugLines = [];
  58061. this._isEnabled = false;
  58062. this._scene = scene;
  58063. this.update();
  58064. this._renderFunction = this.update.bind(this);
  58065. }
  58066. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  58067. get: function () {
  58068. return this._isEnabled;
  58069. },
  58070. set: function (value) {
  58071. if (this._isEnabled === value) {
  58072. return;
  58073. }
  58074. this._isEnabled = value;
  58075. if (value) {
  58076. this._scene.registerBeforeRender(this._renderFunction);
  58077. }
  58078. else {
  58079. this._scene.unregisterBeforeRender(this._renderFunction);
  58080. }
  58081. },
  58082. enumerable: true,
  58083. configurable: true
  58084. });
  58085. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  58086. if (x === void 0) { x = 0; }
  58087. if (y === void 0) { y = 0; }
  58088. if (z === void 0) { z = 0; }
  58089. var tmat = BABYLON.Tmp.Matrix[0];
  58090. var parentBone = bone.getParent();
  58091. tmat.copyFrom(bone.getLocalMatrix());
  58092. if (x !== 0 || y !== 0 || z !== 0) {
  58093. var tmat2 = BABYLON.Tmp.Matrix[1];
  58094. BABYLON.Matrix.IdentityToRef(tmat2);
  58095. tmat2.m[12] = x;
  58096. tmat2.m[13] = y;
  58097. tmat2.m[14] = z;
  58098. tmat2.multiplyToRef(tmat, tmat);
  58099. }
  58100. if (parentBone) {
  58101. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  58102. }
  58103. tmat.multiplyToRef(meshMat, tmat);
  58104. position.x = tmat.m[12];
  58105. position.y = tmat.m[13];
  58106. position.z = tmat.m[14];
  58107. };
  58108. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  58109. var len = bones.length;
  58110. for (var i = 0; i < len; i++) {
  58111. var bone = bones[i];
  58112. var points = this._debugLines[i];
  58113. if (!points) {
  58114. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58115. this._debugLines[i] = points;
  58116. }
  58117. this._getBonePosition(points[0], bone, meshMat);
  58118. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  58119. }
  58120. };
  58121. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  58122. var len = bones.length;
  58123. var boneNum = 0;
  58124. for (var i = len - 1; i >= 0; i--) {
  58125. var childBone = bones[i];
  58126. var parentBone = childBone.getParent();
  58127. if (!parentBone) {
  58128. continue;
  58129. }
  58130. var points = this._debugLines[boneNum];
  58131. if (!points) {
  58132. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58133. this._debugLines[boneNum] = points;
  58134. }
  58135. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  58136. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  58137. boneNum++;
  58138. }
  58139. };
  58140. SkeletonViewer.prototype.update = function () {
  58141. if (this.autoUpdateBonesMatrices) {
  58142. this.skeleton.computeAbsoluteTransforms();
  58143. }
  58144. if (this.skeleton.bones[0].length === undefined) {
  58145. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58146. }
  58147. else {
  58148. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58149. }
  58150. if (!this._debugMesh) {
  58151. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  58152. this._debugMesh.renderingGroupId = this.renderingGroupId;
  58153. }
  58154. else {
  58155. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  58156. }
  58157. this._debugMesh.color = this.color;
  58158. };
  58159. SkeletonViewer.prototype.dispose = function () {
  58160. if (this._debugMesh) {
  58161. this.isEnabled = false;
  58162. this._debugMesh.dispose();
  58163. this._debugMesh = null;
  58164. }
  58165. };
  58166. return SkeletonViewer;
  58167. }());
  58168. Debug.SkeletonViewer = SkeletonViewer;
  58169. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58170. })(BABYLON || (BABYLON = {}));
  58171. //# sourceMappingURL=babylon.skeletonViewer.js.map
  58172. var BABYLON;
  58173. (function (BABYLON) {
  58174. var Debug;
  58175. (function (Debug) {
  58176. var AxesViewer = (function () {
  58177. function AxesViewer(scene, scaleLines) {
  58178. if (scaleLines === void 0) { scaleLines = 1; }
  58179. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58180. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58181. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58182. this.scaleLines = 1;
  58183. this.scaleLines = scaleLines;
  58184. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  58185. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  58186. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  58187. this._xmesh.renderingGroupId = 2;
  58188. this._ymesh.renderingGroupId = 2;
  58189. this._zmesh.renderingGroupId = 2;
  58190. this._xmesh.material.checkReadyOnlyOnce = true;
  58191. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  58192. this._ymesh.material.checkReadyOnlyOnce = true;
  58193. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  58194. this._zmesh.material.checkReadyOnlyOnce = true;
  58195. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  58196. this.scene = scene;
  58197. }
  58198. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  58199. var scaleLines = this.scaleLines;
  58200. var point1 = this._xline[0];
  58201. var point2 = this._xline[1];
  58202. point1.x = position.x;
  58203. point1.y = position.y;
  58204. point1.z = position.z;
  58205. point2.x = point1.x + xaxis.x * scaleLines;
  58206. point2.y = point1.y + xaxis.y * scaleLines;
  58207. point2.z = point1.z + xaxis.z * scaleLines;
  58208. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  58209. point1 = this._yline[0];
  58210. point2 = this._yline[1];
  58211. point1.x = position.x;
  58212. point1.y = position.y;
  58213. point1.z = position.z;
  58214. point2.x = point1.x + yaxis.x * scaleLines;
  58215. point2.y = point1.y + yaxis.y * scaleLines;
  58216. point2.z = point1.z + yaxis.z * scaleLines;
  58217. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  58218. point1 = this._zline[0];
  58219. point2 = this._zline[1];
  58220. point1.x = position.x;
  58221. point1.y = position.y;
  58222. point1.z = position.z;
  58223. point2.x = point1.x + zaxis.x * scaleLines;
  58224. point2.y = point1.y + zaxis.y * scaleLines;
  58225. point2.z = point1.z + zaxis.z * scaleLines;
  58226. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  58227. };
  58228. AxesViewer.prototype.dispose = function () {
  58229. if (this._xmesh) {
  58230. this._xmesh.dispose();
  58231. this._ymesh.dispose();
  58232. this._zmesh.dispose();
  58233. this._xmesh = null;
  58234. this._ymesh = null;
  58235. this._zmesh = null;
  58236. this._xline = null;
  58237. this._yline = null;
  58238. this._zline = null;
  58239. this.scene = null;
  58240. }
  58241. };
  58242. return AxesViewer;
  58243. }());
  58244. Debug.AxesViewer = AxesViewer;
  58245. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58246. })(BABYLON || (BABYLON = {}));
  58247. //# sourceMappingURL=babylon.axesViewer.js.map
  58248. var BABYLON;
  58249. (function (BABYLON) {
  58250. var Debug;
  58251. (function (Debug) {
  58252. var BoneAxesViewer = (function (_super) {
  58253. __extends(BoneAxesViewer, _super);
  58254. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  58255. if (scaleLines === void 0) { scaleLines = 1; }
  58256. var _this = _super.call(this, scene, scaleLines) || this;
  58257. _this.pos = BABYLON.Vector3.Zero();
  58258. _this.xaxis = BABYLON.Vector3.Zero();
  58259. _this.yaxis = BABYLON.Vector3.Zero();
  58260. _this.zaxis = BABYLON.Vector3.Zero();
  58261. _this.mesh = mesh;
  58262. _this.bone = bone;
  58263. return _this;
  58264. }
  58265. BoneAxesViewer.prototype.update = function () {
  58266. var bone = this.bone;
  58267. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  58268. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  58269. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  58270. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  58271. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  58272. };
  58273. BoneAxesViewer.prototype.dispose = function () {
  58274. if (this.pos) {
  58275. this.pos = null;
  58276. this.xaxis = null;
  58277. this.yaxis = null;
  58278. this.zaxis = null;
  58279. this.mesh = null;
  58280. this.bone = null;
  58281. _super.prototype.dispose.call(this);
  58282. }
  58283. };
  58284. return BoneAxesViewer;
  58285. }(Debug.AxesViewer));
  58286. Debug.BoneAxesViewer = BoneAxesViewer;
  58287. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58288. })(BABYLON || (BABYLON = {}));
  58289. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  58290. var BABYLON;
  58291. (function (BABYLON) {
  58292. /**
  58293. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  58294. * It can help converting any input color in a desired output one. This can then be used to create effects
  58295. * from sepia, black and white to sixties or futuristic rendering...
  58296. *
  58297. * The only supported format is currently 3dl.
  58298. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  58299. */
  58300. var ColorGradingTexture = (function (_super) {
  58301. __extends(ColorGradingTexture, _super);
  58302. /**
  58303. * Instantiates a ColorGradingTexture from the following parameters.
  58304. *
  58305. * @param url The location of the color gradind data (currently only supporting 3dl)
  58306. * @param scene The scene the texture will be used in
  58307. */
  58308. function ColorGradingTexture(url, scene) {
  58309. var _this = _super.call(this, scene) || this;
  58310. if (!url) {
  58311. return _this;
  58312. }
  58313. _this._textureMatrix = BABYLON.Matrix.Identity();
  58314. _this.name = url;
  58315. _this.url = url;
  58316. _this.hasAlpha = false;
  58317. _this.isCube = false;
  58318. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58319. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58320. _this.anisotropicFilteringLevel = 1;
  58321. _this._texture = _this._getFromCache(url, true);
  58322. if (!_this._texture) {
  58323. if (!scene.useDelayedTextureLoading) {
  58324. _this.loadTexture();
  58325. }
  58326. else {
  58327. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58328. }
  58329. }
  58330. return _this;
  58331. }
  58332. /**
  58333. * Returns the texture matrix used in most of the material.
  58334. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  58335. */
  58336. ColorGradingTexture.prototype.getTextureMatrix = function () {
  58337. return this._textureMatrix;
  58338. };
  58339. /**
  58340. * Occurs when the file being loaded is a .3dl LUT file.
  58341. */
  58342. ColorGradingTexture.prototype.load3dlTexture = function () {
  58343. var _this = this;
  58344. var mipLevels = 0;
  58345. var floatArrayView = null;
  58346. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58347. this._texture = texture;
  58348. var callback = function (text) {
  58349. var data;
  58350. var tempData;
  58351. var line;
  58352. var lines = text.split('\n');
  58353. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  58354. var maxColor = 0;
  58355. for (var i = 0; i < lines.length; i++) {
  58356. line = lines[i];
  58357. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  58358. continue;
  58359. if (line.indexOf('#') === 0)
  58360. continue;
  58361. var words = line.split(" ");
  58362. if (size === 0) {
  58363. // Number of space + one
  58364. size = words.length;
  58365. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  58366. tempData = new Float32Array(size * size * size * 4);
  58367. continue;
  58368. }
  58369. if (size != 0) {
  58370. var r = Math.max(parseInt(words[0]), 0);
  58371. var g = Math.max(parseInt(words[1]), 0);
  58372. var b = Math.max(parseInt(words[2]), 0);
  58373. maxColor = Math.max(r, maxColor);
  58374. maxColor = Math.max(g, maxColor);
  58375. maxColor = Math.max(b, maxColor);
  58376. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  58377. tempData[pixelStorageIndex + 0] = r;
  58378. tempData[pixelStorageIndex + 1] = g;
  58379. tempData[pixelStorageIndex + 2] = b;
  58380. tempData[pixelStorageIndex + 3] = 0;
  58381. pixelIndexSlice++;
  58382. if (pixelIndexSlice % size == 0) {
  58383. pixelIndexH++;
  58384. pixelIndexSlice = 0;
  58385. if (pixelIndexH % size == 0) {
  58386. pixelIndexW++;
  58387. pixelIndexH = 0;
  58388. }
  58389. }
  58390. }
  58391. }
  58392. for (var i = 0; i < tempData.length; i++) {
  58393. var value = tempData[i];
  58394. data[i] = (value / maxColor * 255);
  58395. }
  58396. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  58397. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  58398. };
  58399. BABYLON.Tools.LoadFile(this.url, callback);
  58400. return this._texture;
  58401. };
  58402. /**
  58403. * Starts the loading process of the texture.
  58404. */
  58405. ColorGradingTexture.prototype.loadTexture = function () {
  58406. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  58407. this.load3dlTexture();
  58408. }
  58409. };
  58410. /**
  58411. * Clones the color gradind texture.
  58412. */
  58413. ColorGradingTexture.prototype.clone = function () {
  58414. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  58415. // Base texture
  58416. newTexture.level = this.level;
  58417. return newTexture;
  58418. };
  58419. /**
  58420. * Called during delayed load for textures.
  58421. */
  58422. ColorGradingTexture.prototype.delayLoad = function () {
  58423. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58424. return;
  58425. }
  58426. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58427. this._texture = this._getFromCache(this.url, true);
  58428. if (!this._texture) {
  58429. this.loadTexture();
  58430. }
  58431. };
  58432. /**
  58433. * Binds the color grading to the shader.
  58434. * @param colorGrading The texture to bind
  58435. * @param effect The effect to bind to
  58436. */
  58437. ColorGradingTexture.Bind = function (colorGrading, effect) {
  58438. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  58439. var x = colorGrading.level; // Texture Level
  58440. var y = colorGrading.getSize().height; // Texture Size example with 8
  58441. var z = y - 1.0; // SizeMinusOne 8 - 1
  58442. var w = 1 / y; // Space of 1 slice 1 / 8
  58443. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  58444. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  58445. 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
  58446. 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
  58447. 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
  58448. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  58449. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  58450. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  58451. };
  58452. /**
  58453. * Prepare the list of uniforms associated with the ColorGrading effects.
  58454. * @param uniformsList The list of uniforms used in the effect
  58455. * @param samplersList The list of samplers used in the effect
  58456. */
  58457. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  58458. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  58459. samplersList.push("cameraColorGrading2DSampler");
  58460. };
  58461. /**
  58462. * Parses a color grading texture serialized by Babylon.
  58463. * @param parsedTexture The texture information being parsedTexture
  58464. * @param scene The scene to load the texture in
  58465. * @param rootUrl The root url of the data assets to load
  58466. * @return A color gradind texture
  58467. */
  58468. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58469. var texture = null;
  58470. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  58471. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  58472. texture.name = parsedTexture.name;
  58473. texture.level = parsedTexture.level;
  58474. }
  58475. return texture;
  58476. };
  58477. /**
  58478. * Serializes the LUT texture to json format.
  58479. */
  58480. ColorGradingTexture.prototype.serialize = function () {
  58481. if (!this.name) {
  58482. return null;
  58483. }
  58484. var serializationObject = {};
  58485. serializationObject.name = this.name;
  58486. serializationObject.level = this.level;
  58487. serializationObject.customType = "BABYLON.ColorGradingTexture";
  58488. return serializationObject;
  58489. };
  58490. return ColorGradingTexture;
  58491. }(BABYLON.BaseTexture));
  58492. /**
  58493. * Empty line regex stored for GC.
  58494. */
  58495. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  58496. BABYLON.ColorGradingTexture = ColorGradingTexture;
  58497. })(BABYLON || (BABYLON = {}));
  58498. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  58499. var BABYLON;
  58500. (function (BABYLON) {
  58501. /**
  58502. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  58503. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  58504. * 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;
  58505. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  58506. */
  58507. var ColorCurves = (function () {
  58508. function ColorCurves() {
  58509. this._dirty = true;
  58510. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  58511. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  58512. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  58513. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  58514. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  58515. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  58516. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  58517. this._globalHue = 30;
  58518. this._globalDensity = 0;
  58519. this._globalSaturation = 0;
  58520. this._globalExposure = 0;
  58521. this._highlightsHue = 30;
  58522. this._highlightsDensity = 0;
  58523. this._highlightsSaturation = 0;
  58524. this._highlightsExposure = 0;
  58525. this._midtonesHue = 30;
  58526. this._midtonesDensity = 0;
  58527. this._midtonesSaturation = 0;
  58528. this._midtonesExposure = 0;
  58529. this._shadowsHue = 30;
  58530. this._shadowsDensity = 0;
  58531. this._shadowsSaturation = 0;
  58532. this._shadowsExposure = 0;
  58533. }
  58534. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  58535. /**
  58536. * Gets the global Hue value.
  58537. * 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).
  58538. */
  58539. get: function () {
  58540. return this._globalHue;
  58541. },
  58542. /**
  58543. * Sets the global Hue value.
  58544. * 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).
  58545. */
  58546. set: function (value) {
  58547. this._globalHue = value;
  58548. this._dirty = true;
  58549. },
  58550. enumerable: true,
  58551. configurable: true
  58552. });
  58553. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  58554. /**
  58555. * Gets the global Density value.
  58556. * 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.
  58557. * Values less than zero provide a filter of opposite hue.
  58558. */
  58559. get: function () {
  58560. return this._globalDensity;
  58561. },
  58562. /**
  58563. * Sets the global Density value.
  58564. * 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.
  58565. * Values less than zero provide a filter of opposite hue.
  58566. */
  58567. set: function (value) {
  58568. this._globalDensity = value;
  58569. this._dirty = true;
  58570. },
  58571. enumerable: true,
  58572. configurable: true
  58573. });
  58574. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  58575. /**
  58576. * Gets the global Saturation value.
  58577. * 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.
  58578. */
  58579. get: function () {
  58580. return this._globalSaturation;
  58581. },
  58582. /**
  58583. * Sets the global Saturation value.
  58584. * 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.
  58585. */
  58586. set: function (value) {
  58587. this._globalSaturation = value;
  58588. this._dirty = true;
  58589. },
  58590. enumerable: true,
  58591. configurable: true
  58592. });
  58593. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  58594. /**
  58595. * Gets the highlights Hue value.
  58596. * 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).
  58597. */
  58598. get: function () {
  58599. return this._highlightsHue;
  58600. },
  58601. /**
  58602. * Sets the highlights Hue value.
  58603. * 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).
  58604. */
  58605. set: function (value) {
  58606. this._highlightsHue = value;
  58607. this._dirty = true;
  58608. },
  58609. enumerable: true,
  58610. configurable: true
  58611. });
  58612. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  58613. /**
  58614. * Gets the highlights Density value.
  58615. * 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.
  58616. * Values less than zero provide a filter of opposite hue.
  58617. */
  58618. get: function () {
  58619. return this._highlightsDensity;
  58620. },
  58621. /**
  58622. * Sets the highlights Density value.
  58623. * 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.
  58624. * Values less than zero provide a filter of opposite hue.
  58625. */
  58626. set: function (value) {
  58627. this._highlightsDensity = value;
  58628. this._dirty = true;
  58629. },
  58630. enumerable: true,
  58631. configurable: true
  58632. });
  58633. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  58634. /**
  58635. * Gets the highlights Saturation value.
  58636. * 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.
  58637. */
  58638. get: function () {
  58639. return this._highlightsSaturation;
  58640. },
  58641. /**
  58642. * Sets the highlights Saturation value.
  58643. * 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.
  58644. */
  58645. set: function (value) {
  58646. this._highlightsSaturation = value;
  58647. this._dirty = true;
  58648. },
  58649. enumerable: true,
  58650. configurable: true
  58651. });
  58652. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  58653. /**
  58654. * Gets the highlights Exposure value.
  58655. * 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.
  58656. */
  58657. get: function () {
  58658. return this._highlightsExposure;
  58659. },
  58660. /**
  58661. * Sets the highlights Exposure value.
  58662. * 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.
  58663. */
  58664. set: function (value) {
  58665. this._highlightsExposure = value;
  58666. this._dirty = true;
  58667. },
  58668. enumerable: true,
  58669. configurable: true
  58670. });
  58671. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  58672. /**
  58673. * Gets the midtones Hue value.
  58674. * 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).
  58675. */
  58676. get: function () {
  58677. return this._midtonesHue;
  58678. },
  58679. /**
  58680. * Sets the midtones Hue value.
  58681. * 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).
  58682. */
  58683. set: function (value) {
  58684. this._midtonesHue = value;
  58685. this._dirty = true;
  58686. },
  58687. enumerable: true,
  58688. configurable: true
  58689. });
  58690. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  58691. /**
  58692. * Gets the midtones Density value.
  58693. * 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.
  58694. * Values less than zero provide a filter of opposite hue.
  58695. */
  58696. get: function () {
  58697. return this._midtonesDensity;
  58698. },
  58699. /**
  58700. * Sets the midtones Density value.
  58701. * 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.
  58702. * Values less than zero provide a filter of opposite hue.
  58703. */
  58704. set: function (value) {
  58705. this._midtonesDensity = value;
  58706. this._dirty = true;
  58707. },
  58708. enumerable: true,
  58709. configurable: true
  58710. });
  58711. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  58712. /**
  58713. * Gets the midtones Saturation value.
  58714. * 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.
  58715. */
  58716. get: function () {
  58717. return this._midtonesSaturation;
  58718. },
  58719. /**
  58720. * Sets the midtones Saturation value.
  58721. * 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.
  58722. */
  58723. set: function (value) {
  58724. this._midtonesSaturation = value;
  58725. this._dirty = true;
  58726. },
  58727. enumerable: true,
  58728. configurable: true
  58729. });
  58730. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  58731. /**
  58732. * Gets the midtones Exposure value.
  58733. * 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.
  58734. */
  58735. get: function () {
  58736. return this._midtonesExposure;
  58737. },
  58738. /**
  58739. * Sets the midtones Exposure value.
  58740. * 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.
  58741. */
  58742. set: function (value) {
  58743. this._midtonesExposure = value;
  58744. this._dirty = true;
  58745. },
  58746. enumerable: true,
  58747. configurable: true
  58748. });
  58749. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  58750. /**
  58751. * Gets the shadows Hue value.
  58752. * 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).
  58753. */
  58754. get: function () {
  58755. return this._shadowsHue;
  58756. },
  58757. /**
  58758. * Sets the shadows Hue value.
  58759. * 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).
  58760. */
  58761. set: function (value) {
  58762. this._shadowsHue = value;
  58763. this._dirty = true;
  58764. },
  58765. enumerable: true,
  58766. configurable: true
  58767. });
  58768. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  58769. /**
  58770. * Gets the shadows Density value.
  58771. * 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.
  58772. * Values less than zero provide a filter of opposite hue.
  58773. */
  58774. get: function () {
  58775. return this._shadowsDensity;
  58776. },
  58777. /**
  58778. * Sets the shadows Density value.
  58779. * 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.
  58780. * Values less than zero provide a filter of opposite hue.
  58781. */
  58782. set: function (value) {
  58783. this._shadowsDensity = value;
  58784. this._dirty = true;
  58785. },
  58786. enumerable: true,
  58787. configurable: true
  58788. });
  58789. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  58790. /**
  58791. * Gets the shadows Saturation value.
  58792. * 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.
  58793. */
  58794. get: function () {
  58795. return this._shadowsSaturation;
  58796. },
  58797. /**
  58798. * Sets the shadows Saturation value.
  58799. * 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.
  58800. */
  58801. set: function (value) {
  58802. this._shadowsSaturation = value;
  58803. this._dirty = true;
  58804. },
  58805. enumerable: true,
  58806. configurable: true
  58807. });
  58808. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  58809. /**
  58810. * Gets the shadows Exposure value.
  58811. * 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.
  58812. */
  58813. get: function () {
  58814. return this._shadowsExposure;
  58815. },
  58816. /**
  58817. * Sets the shadows Exposure value.
  58818. * 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.
  58819. */
  58820. set: function (value) {
  58821. this._shadowsExposure = value;
  58822. this._dirty = true;
  58823. },
  58824. enumerable: true,
  58825. configurable: true
  58826. });
  58827. /**
  58828. * Binds the color curves to the shader.
  58829. * @param colorCurves The color curve to bind
  58830. * @param effect The effect to bind to
  58831. */
  58832. ColorCurves.Bind = function (colorCurves, effect) {
  58833. if (colorCurves._dirty) {
  58834. colorCurves._dirty = false;
  58835. // Fill in global info.
  58836. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  58837. // Compute highlights info.
  58838. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  58839. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  58840. // Compute midtones info.
  58841. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  58842. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  58843. // Compute shadows info.
  58844. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  58845. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  58846. // Compute deltas (neutral is midtones).
  58847. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  58848. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  58849. }
  58850. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  58851. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  58852. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  58853. };
  58854. /**
  58855. * Prepare the list of uniforms associated with the ColorCurves effects.
  58856. * @param uniformsList The list of uniforms used in the effect
  58857. */
  58858. ColorCurves.PrepareUniforms = function (uniformsList) {
  58859. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  58860. };
  58861. /**
  58862. * Returns color grading data based on a hue, density, saturation and exposure value.
  58863. * @param filterHue The hue of the color filter.
  58864. * @param filterDensity The density of the color filter.
  58865. * @param saturation The saturation.
  58866. * @param exposure The exposure.
  58867. * @param result The result data container.
  58868. */
  58869. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  58870. if (hue == null) {
  58871. return;
  58872. }
  58873. hue = ColorCurves.clamp(hue, 0, 360);
  58874. density = ColorCurves.clamp(density, -100, 100);
  58875. saturation = ColorCurves.clamp(saturation, -100, 100);
  58876. exposure = ColorCurves.clamp(exposure, -100, 100);
  58877. // Remap the slider/config filter density with non-linear mapping and also scale by half
  58878. // so that the maximum filter density is only 50% control. This provides fine control
  58879. // for small values and reasonable range.
  58880. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  58881. density *= 0.5;
  58882. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  58883. if (density < 0) {
  58884. density *= -1;
  58885. hue = (hue + 180) % 360;
  58886. }
  58887. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  58888. result.scaleToRef(2, result);
  58889. result.a = 1 + 0.01 * saturation;
  58890. };
  58891. /**
  58892. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  58893. * @param value The input slider value in range [-100,100].
  58894. * @returns Adjusted value.
  58895. */
  58896. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  58897. value /= 100;
  58898. var x = Math.abs(value);
  58899. x = Math.pow(x, 2);
  58900. if (value < 0) {
  58901. x *= -1;
  58902. }
  58903. x *= 100;
  58904. return x;
  58905. };
  58906. /**
  58907. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  58908. * @param hue The hue (H) input.
  58909. * @param saturation The saturation (S) input.
  58910. * @param brightness The brightness (B) input.
  58911. * @result An RGBA color represented as Vector4.
  58912. */
  58913. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  58914. var h = ColorCurves.clamp(hue, 0, 360);
  58915. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  58916. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  58917. if (s === 0) {
  58918. result.r = v;
  58919. result.g = v;
  58920. result.b = v;
  58921. }
  58922. else {
  58923. // sector 0 to 5
  58924. h /= 60;
  58925. var i = Math.floor(h);
  58926. // fractional part of h
  58927. var f = h - i;
  58928. var p = v * (1 - s);
  58929. var q = v * (1 - s * f);
  58930. var t = v * (1 - s * (1 - f));
  58931. switch (i) {
  58932. case 0:
  58933. result.r = v;
  58934. result.g = t;
  58935. result.b = p;
  58936. break;
  58937. case 1:
  58938. result.r = q;
  58939. result.g = v;
  58940. result.b = p;
  58941. break;
  58942. case 2:
  58943. result.r = p;
  58944. result.g = v;
  58945. result.b = t;
  58946. break;
  58947. case 3:
  58948. result.r = p;
  58949. result.g = q;
  58950. result.b = v;
  58951. break;
  58952. case 4:
  58953. result.r = t;
  58954. result.g = p;
  58955. result.b = v;
  58956. break;
  58957. default:
  58958. result.r = v;
  58959. result.g = p;
  58960. result.b = q;
  58961. break;
  58962. }
  58963. }
  58964. result.a = 1;
  58965. };
  58966. /**
  58967. * Returns a value clamped between min and max
  58968. * @param value The value to clamp
  58969. * @param min The minimum of value
  58970. * @param max The maximum of value
  58971. * @returns The clamped value.
  58972. */
  58973. ColorCurves.clamp = function (value, min, max) {
  58974. return Math.min(Math.max(value, min), max);
  58975. };
  58976. /**
  58977. * Clones the current color curve instance.
  58978. * @return The cloned curves
  58979. */
  58980. ColorCurves.prototype.clone = function () {
  58981. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  58982. };
  58983. /**
  58984. * Serializes the current color curve instance to a json representation.
  58985. * @return a JSON representation
  58986. */
  58987. ColorCurves.prototype.serialize = function () {
  58988. return BABYLON.SerializationHelper.Serialize(this);
  58989. };
  58990. /**
  58991. * Parses the color curve from a json representation.
  58992. * @param source the JSON source to parse
  58993. * @return The parsed curves
  58994. */
  58995. ColorCurves.Parse = function (source) {
  58996. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  58997. };
  58998. return ColorCurves;
  58999. }());
  59000. __decorate([
  59001. BABYLON.serialize()
  59002. ], ColorCurves.prototype, "_globalHue", void 0);
  59003. __decorate([
  59004. BABYLON.serialize()
  59005. ], ColorCurves.prototype, "_globalDensity", void 0);
  59006. __decorate([
  59007. BABYLON.serialize()
  59008. ], ColorCurves.prototype, "_globalSaturation", void 0);
  59009. __decorate([
  59010. BABYLON.serialize()
  59011. ], ColorCurves.prototype, "_globalExposure", void 0);
  59012. __decorate([
  59013. BABYLON.serialize()
  59014. ], ColorCurves.prototype, "_highlightsHue", void 0);
  59015. __decorate([
  59016. BABYLON.serialize()
  59017. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  59018. __decorate([
  59019. BABYLON.serialize()
  59020. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  59021. __decorate([
  59022. BABYLON.serialize()
  59023. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  59024. __decorate([
  59025. BABYLON.serialize()
  59026. ], ColorCurves.prototype, "_midtonesHue", void 0);
  59027. __decorate([
  59028. BABYLON.serialize()
  59029. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  59030. __decorate([
  59031. BABYLON.serialize()
  59032. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  59033. __decorate([
  59034. BABYLON.serialize()
  59035. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  59036. BABYLON.ColorCurves = ColorCurves;
  59037. })(BABYLON || (BABYLON = {}));
  59038. //# sourceMappingURL=babylon.colorCurves.js.map
  59039. var BABYLON;
  59040. (function (BABYLON) {
  59041. var PBRMaterialDefines = (function (_super) {
  59042. __extends(PBRMaterialDefines, _super);
  59043. function PBRMaterialDefines() {
  59044. var _this = _super.call(this) || this;
  59045. _this.ALBEDO = false;
  59046. _this.AMBIENT = false;
  59047. _this.OPACITY = false;
  59048. _this.OPACITYRGB = false;
  59049. _this.REFLECTION = false;
  59050. _this.EMISSIVE = false;
  59051. _this.REFLECTIVITY = false;
  59052. _this.BUMP = false;
  59053. _this.PARALLAX = false;
  59054. _this.PARALLAXOCCLUSION = false;
  59055. _this.SPECULAROVERALPHA = false;
  59056. _this.CLIPPLANE = false;
  59057. _this.ALPHATEST = false;
  59058. _this.ALPHAFROMALBEDO = false;
  59059. _this.POINTSIZE = false;
  59060. _this.FOG = false;
  59061. _this.SPECULARTERM = false;
  59062. _this.OPACITYFRESNEL = false;
  59063. _this.EMISSIVEFRESNEL = false;
  59064. _this.FRESNEL = false;
  59065. _this.NORMAL = false;
  59066. _this.TANGENT = false;
  59067. _this.UV1 = false;
  59068. _this.UV2 = false;
  59069. _this.VERTEXCOLOR = false;
  59070. _this.VERTEXALPHA = false;
  59071. _this.NUM_BONE_INFLUENCERS = 0;
  59072. _this.BonesPerMesh = 0;
  59073. _this.INSTANCES = false;
  59074. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  59075. _this.MICROSURFACEAUTOMATIC = false;
  59076. _this.EMISSIVEASILLUMINATION = false;
  59077. _this.LINKEMISSIVEWITHALBEDO = false;
  59078. _this.LIGHTMAP = false;
  59079. _this.USELIGHTMAPASSHADOWMAP = false;
  59080. _this.REFLECTIONMAP_3D = false;
  59081. _this.REFLECTIONMAP_SPHERICAL = false;
  59082. _this.REFLECTIONMAP_PLANAR = false;
  59083. _this.REFLECTIONMAP_CUBIC = false;
  59084. _this.REFLECTIONMAP_PROJECTION = false;
  59085. _this.REFLECTIONMAP_SKYBOX = false;
  59086. _this.REFLECTIONMAP_EXPLICIT = false;
  59087. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  59088. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  59089. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  59090. _this.INVERTCUBICMAP = false;
  59091. _this.LOGARITHMICDEPTH = false;
  59092. _this.CAMERATONEMAP = false;
  59093. _this.CAMERACONTRAST = false;
  59094. _this.CAMERACOLORGRADING = false;
  59095. _this.CAMERACOLORCURVES = false;
  59096. _this.OVERLOADEDVALUES = false;
  59097. _this.OVERLOADEDSHADOWVALUES = false;
  59098. _this.USESPHERICALFROMREFLECTIONMAP = false;
  59099. _this.REFRACTION = false;
  59100. _this.REFRACTIONMAP_3D = false;
  59101. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  59102. _this.REFRACTIONMAPINLINEARSPACE = false;
  59103. _this.LODBASEDMICROSFURACE = false;
  59104. _this.USEPHYSICALLIGHTFALLOFF = false;
  59105. _this.RADIANCEOVERALPHA = false;
  59106. _this.USEPMREMREFLECTION = false;
  59107. _this.USEPMREMREFRACTION = false;
  59108. _this.INVERTNORMALMAPX = false;
  59109. _this.INVERTNORMALMAPY = false;
  59110. _this.TWOSIDEDLIGHTING = false;
  59111. _this.SHADOWFULLFLOAT = false;
  59112. _this.METALLICWORKFLOW = false;
  59113. _this.METALLICROUGHNESSMAP = false;
  59114. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  59115. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  59116. _this.rebuild();
  59117. return _this;
  59118. }
  59119. return PBRMaterialDefines;
  59120. }(BABYLON.MaterialDefines));
  59121. /**
  59122. * The Physically based material of BJS.
  59123. *
  59124. * This offers the main features of a standard PBR material.
  59125. * For more information, please refer to the documentation :
  59126. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  59127. */
  59128. var PBRMaterial = (function (_super) {
  59129. __extends(PBRMaterial, _super);
  59130. /**
  59131. * Instantiates a new PBRMaterial instance.
  59132. *
  59133. * @param name The material name
  59134. * @param scene The scene the material will be use in.
  59135. */
  59136. function PBRMaterial(name, scene) {
  59137. var _this = _super.call(this, name, scene) || this;
  59138. /**
  59139. * Intensity of the direct lights e.g. the four lights available in your scene.
  59140. * This impacts both the direct diffuse and specular highlights.
  59141. */
  59142. _this.directIntensity = 1.0;
  59143. /**
  59144. * Intensity of the emissive part of the material.
  59145. * This helps controlling the emissive effect without modifying the emissive color.
  59146. */
  59147. _this.emissiveIntensity = 1.0;
  59148. /**
  59149. * Intensity of the environment e.g. how much the environment will light the object
  59150. * either through harmonics for rough material or through the refelction for shiny ones.
  59151. */
  59152. _this.environmentIntensity = 1.0;
  59153. /**
  59154. * This is a special control allowing the reduction of the specular highlights coming from the
  59155. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  59156. */
  59157. _this.specularIntensity = 1.0;
  59158. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  59159. /**
  59160. * Debug Control allowing disabling the bump map on this material.
  59161. */
  59162. _this.disableBumpMap = false;
  59163. /**
  59164. * Debug Control helping enforcing or dropping the darkness of shadows.
  59165. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  59166. */
  59167. _this.overloadedShadowIntensity = 1.0;
  59168. /**
  59169. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  59170. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  59171. */
  59172. _this.overloadedShadeIntensity = 1.0;
  59173. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  59174. /**
  59175. * The camera exposure used on this material.
  59176. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  59177. * This corresponds to a photographic exposure.
  59178. */
  59179. _this.cameraExposure = 1.0;
  59180. /**
  59181. * The camera contrast used on this material.
  59182. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  59183. */
  59184. _this.cameraContrast = 1.0;
  59185. /**
  59186. * Color Grading 2D Lookup Texture.
  59187. * This allows special effects like sepia, black and white to sixties rendering style.
  59188. */
  59189. _this.cameraColorGradingTexture = null;
  59190. /**
  59191. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  59192. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  59193. * 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;
  59194. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  59195. */
  59196. _this.cameraColorCurves = null;
  59197. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  59198. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  59199. /**
  59200. * Debug Control allowing to overload the ambient color.
  59201. * This as to be use with the overloadedAmbientIntensity parameter.
  59202. */
  59203. _this.overloadedAmbient = BABYLON.Color3.White();
  59204. /**
  59205. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  59206. */
  59207. _this.overloadedAmbientIntensity = 0.0;
  59208. /**
  59209. * Debug Control allowing to overload the albedo color.
  59210. * This as to be use with the overloadedAlbedoIntensity parameter.
  59211. */
  59212. _this.overloadedAlbedo = BABYLON.Color3.White();
  59213. /**
  59214. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  59215. */
  59216. _this.overloadedAlbedoIntensity = 0.0;
  59217. /**
  59218. * Debug Control allowing to overload the reflectivity color.
  59219. * This as to be use with the overloadedReflectivityIntensity parameter.
  59220. */
  59221. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  59222. /**
  59223. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  59224. */
  59225. _this.overloadedReflectivityIntensity = 0.0;
  59226. /**
  59227. * Debug Control allowing to overload the emissive color.
  59228. * This as to be use with the overloadedEmissiveIntensity parameter.
  59229. */
  59230. _this.overloadedEmissive = BABYLON.Color3.White();
  59231. /**
  59232. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  59233. */
  59234. _this.overloadedEmissiveIntensity = 0.0;
  59235. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  59236. /**
  59237. * Debug Control allowing to overload the reflection color.
  59238. * This as to be use with the overloadedReflectionIntensity parameter.
  59239. */
  59240. _this.overloadedReflection = BABYLON.Color3.White();
  59241. /**
  59242. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  59243. */
  59244. _this.overloadedReflectionIntensity = 0.0;
  59245. /**
  59246. * Debug Control allowing to overload the microsurface.
  59247. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  59248. */
  59249. _this.overloadedMicroSurface = 0.0;
  59250. /**
  59251. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  59252. */
  59253. _this.overloadedMicroSurfaceIntensity = 0.0;
  59254. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  59255. /**
  59256. * AKA Occlusion Texture Intensity in other nomenclature.
  59257. */
  59258. _this.ambientTextureStrength = 1.0;
  59259. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  59260. /**
  59261. * AKA Diffuse Color in other nomenclature.
  59262. */
  59263. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  59264. /**
  59265. * AKA Specular Color in other nomenclature.
  59266. */
  59267. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  59268. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  59269. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  59270. /**
  59271. * AKA Glossiness in other nomenclature.
  59272. */
  59273. _this.microSurface = 0.9;
  59274. /**
  59275. * source material index of refraction (IOR)' / 'destination material IOR.
  59276. */
  59277. _this.indexOfRefraction = 0.66;
  59278. /**
  59279. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  59280. */
  59281. _this.invertRefractionY = false;
  59282. /**
  59283. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  59284. * Materials half opaque for instance using refraction could benefit from this control.
  59285. */
  59286. _this.linkRefractionWithTransparency = false;
  59287. /**
  59288. * The emissive and albedo are linked to never be more than one (Energy conservation).
  59289. */
  59290. _this.linkEmissiveWithAlbedo = false;
  59291. _this.useLightmapAsShadowmap = false;
  59292. /**
  59293. * In this mode, the emissive informtaion will always be added to the lighting once.
  59294. * A light for instance can be thought as emissive.
  59295. */
  59296. _this.useEmissiveAsIllumination = false;
  59297. /**
  59298. * Secifies that the alpha is coming form the albedo channel alpha channel.
  59299. */
  59300. _this.useAlphaFromAlbedoTexture = false;
  59301. /**
  59302. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  59303. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  59304. */
  59305. _this.useSpecularOverAlpha = true;
  59306. /**
  59307. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  59308. */
  59309. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  59310. /**
  59311. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  59312. */
  59313. _this.useRoughnessFromMetallicTextureAlpha = true;
  59314. /**
  59315. * Specifies if the metallic texture contains the roughness information in its green channel.
  59316. */
  59317. _this.useRoughnessFromMetallicTextureGreen = false;
  59318. /**
  59319. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  59320. * The material will try to infer what glossiness each pixel should be.
  59321. */
  59322. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  59323. /**
  59324. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  59325. * the creation of the material.
  59326. */
  59327. _this.useScalarInLinearSpace = false;
  59328. /**
  59329. * BJS is using an harcoded light falloff based on a manually sets up range.
  59330. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  59331. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  59332. */
  59333. _this.usePhysicalLightFalloff = true;
  59334. /**
  59335. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  59336. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  59337. */
  59338. _this.useRadianceOverAlpha = true;
  59339. /**
  59340. * Allows using the bump map in parallax mode.
  59341. */
  59342. _this.useParallax = false;
  59343. /**
  59344. * Allows using the bump map in parallax occlusion mode.
  59345. */
  59346. _this.useParallaxOcclusion = false;
  59347. /**
  59348. * Controls the scale bias of the parallax mode.
  59349. */
  59350. _this.parallaxScaleBias = 0.05;
  59351. /**
  59352. * If sets to true, disables all the lights affecting the material.
  59353. */
  59354. _this.disableLighting = false;
  59355. /**
  59356. * Number of Simultaneous lights allowed on the material.
  59357. */
  59358. _this.maxSimultaneousLights = 4;
  59359. /**
  59360. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  59361. */
  59362. _this.invertNormalMapX = false;
  59363. /**
  59364. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  59365. */
  59366. _this.invertNormalMapY = false;
  59367. /**
  59368. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  59369. */
  59370. _this.twoSidedLighting = false;
  59371. _this._renderTargets = new BABYLON.SmartArray(16);
  59372. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  59373. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  59374. _this._tempColor = new BABYLON.Color3();
  59375. _this._defines = new PBRMaterialDefines();
  59376. _this._cachedDefines = new PBRMaterialDefines();
  59377. _this._myScene = null;
  59378. _this._myShadowGenerator = null;
  59379. _this._cachedDefines.BonesPerMesh = -1;
  59380. _this.getRenderTargetTextures = function () {
  59381. _this._renderTargets.reset();
  59382. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  59383. _this._renderTargets.push(_this.reflectionTexture);
  59384. }
  59385. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  59386. _this._renderTargets.push(_this.refractionTexture);
  59387. }
  59388. return _this._renderTargets;
  59389. };
  59390. return _this;
  59391. }
  59392. PBRMaterial.prototype.getClassName = function () {
  59393. return "PBRMaterial";
  59394. };
  59395. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  59396. get: function () {
  59397. return this._useLogarithmicDepth;
  59398. },
  59399. set: function (value) {
  59400. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  59401. },
  59402. enumerable: true,
  59403. configurable: true
  59404. });
  59405. PBRMaterial.prototype.needAlphaBlending = function () {
  59406. if (this.linkRefractionWithTransparency) {
  59407. return false;
  59408. }
  59409. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  59410. };
  59411. PBRMaterial.prototype.needAlphaTesting = function () {
  59412. if (this.linkRefractionWithTransparency) {
  59413. return false;
  59414. }
  59415. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  59416. };
  59417. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  59418. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  59419. };
  59420. PBRMaterial.prototype.getAlphaTestTexture = function () {
  59421. return this.albedoTexture;
  59422. };
  59423. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59424. if (!mesh) {
  59425. return true;
  59426. }
  59427. if (this._defines.INSTANCES !== useInstances) {
  59428. return false;
  59429. }
  59430. return false;
  59431. };
  59432. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  59433. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  59434. };
  59435. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  59436. if (!useScalarInLinear) {
  59437. color.toLinearSpaceToRef(ref);
  59438. }
  59439. else {
  59440. ref.r = color.r;
  59441. ref.g = color.g;
  59442. ref.b = color.b;
  59443. }
  59444. };
  59445. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  59446. var lightIndex = 0;
  59447. var depthValuesAlreadySet = false;
  59448. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  59449. var light = _a[_i];
  59450. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  59451. // GAMMA CORRECTION.
  59452. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  59453. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  59454. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  59455. if (defines["SPECULARTERM"]) {
  59456. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  59457. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  59458. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  59459. }
  59460. // Shadows
  59461. if (scene.shadowsEnabled) {
  59462. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  59463. }
  59464. lightIndex++;
  59465. if (lightIndex === maxSimultaneousLights)
  59466. break;
  59467. }
  59468. };
  59469. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  59470. if (this.isFrozen) {
  59471. if (this._wasPreviouslyReady) {
  59472. return true;
  59473. }
  59474. }
  59475. var scene = this.getScene();
  59476. var engine = scene.getEngine();
  59477. var needNormals = false;
  59478. var needUVs = false;
  59479. this._defines.reset();
  59480. if (scene.lightsEnabled && !this.disableLighting) {
  59481. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  59482. }
  59483. if (!this.checkReadyOnEveryCall) {
  59484. if (this._renderId === scene.getRenderId()) {
  59485. if (this._checkCache(scene, mesh, useInstances)) {
  59486. return true;
  59487. }
  59488. }
  59489. }
  59490. if (scene.texturesEnabled) {
  59491. if (scene.getEngine().getCaps().textureLOD) {
  59492. this._defines.LODBASEDMICROSFURACE = true;
  59493. }
  59494. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  59495. if (!this.albedoTexture.isReady()) {
  59496. return false;
  59497. }
  59498. else {
  59499. needUVs = true;
  59500. this._defines.ALBEDO = true;
  59501. }
  59502. }
  59503. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  59504. if (!this.ambientTexture.isReady()) {
  59505. return false;
  59506. }
  59507. else {
  59508. needUVs = true;
  59509. this._defines.AMBIENT = true;
  59510. }
  59511. }
  59512. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  59513. if (!this.opacityTexture.isReady()) {
  59514. return false;
  59515. }
  59516. else {
  59517. needUVs = true;
  59518. this._defines.OPACITY = true;
  59519. if (this.opacityTexture.getAlphaFromRGB) {
  59520. this._defines.OPACITYRGB = true;
  59521. }
  59522. }
  59523. }
  59524. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  59525. if (!this.reflectionTexture.isReady()) {
  59526. return false;
  59527. }
  59528. else {
  59529. needNormals = true;
  59530. this._defines.REFLECTION = true;
  59531. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  59532. this._defines.INVERTCUBICMAP = true;
  59533. }
  59534. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  59535. switch (this.reflectionTexture.coordinatesMode) {
  59536. case BABYLON.Texture.CUBIC_MODE:
  59537. case BABYLON.Texture.INVCUBIC_MODE:
  59538. this._defines.REFLECTIONMAP_CUBIC = true;
  59539. break;
  59540. case BABYLON.Texture.EXPLICIT_MODE:
  59541. this._defines.REFLECTIONMAP_EXPLICIT = true;
  59542. break;
  59543. case BABYLON.Texture.PLANAR_MODE:
  59544. this._defines.REFLECTIONMAP_PLANAR = true;
  59545. break;
  59546. case BABYLON.Texture.PROJECTION_MODE:
  59547. this._defines.REFLECTIONMAP_PROJECTION = true;
  59548. break;
  59549. case BABYLON.Texture.SKYBOX_MODE:
  59550. this._defines.REFLECTIONMAP_SKYBOX = true;
  59551. break;
  59552. case BABYLON.Texture.SPHERICAL_MODE:
  59553. this._defines.REFLECTIONMAP_SPHERICAL = true;
  59554. break;
  59555. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  59556. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  59557. break;
  59558. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  59559. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  59560. break;
  59561. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  59562. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  59563. break;
  59564. }
  59565. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  59566. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  59567. needNormals = true;
  59568. if (this.reflectionTexture.isPMREM) {
  59569. this._defines.USEPMREMREFLECTION = true;
  59570. }
  59571. }
  59572. }
  59573. }
  59574. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  59575. if (!this.lightmapTexture.isReady()) {
  59576. return false;
  59577. }
  59578. else {
  59579. needUVs = true;
  59580. this._defines.LIGHTMAP = true;
  59581. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  59582. }
  59583. }
  59584. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  59585. if (!this.emissiveTexture.isReady()) {
  59586. return false;
  59587. }
  59588. else {
  59589. needUVs = true;
  59590. this._defines.EMISSIVE = true;
  59591. }
  59592. }
  59593. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  59594. if (this.metallicTexture) {
  59595. if (!this.metallicTexture.isReady()) {
  59596. return false;
  59597. }
  59598. else {
  59599. needUVs = true;
  59600. this._defines.METALLICWORKFLOW = true;
  59601. this._defines.METALLICROUGHNESSMAP = true;
  59602. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  59603. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  59604. }
  59605. }
  59606. else if (this.reflectivityTexture) {
  59607. if (!this.reflectivityTexture.isReady()) {
  59608. return false;
  59609. }
  59610. else {
  59611. needUVs = true;
  59612. this._defines.REFLECTIVITY = true;
  59613. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  59614. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  59615. }
  59616. }
  59617. }
  59618. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  59619. if (!this.bumpTexture.isReady()) {
  59620. return false;
  59621. }
  59622. else {
  59623. needUVs = true;
  59624. this._defines.BUMP = true;
  59625. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  59626. this._defines.PARALLAX = true;
  59627. if (this.useParallaxOcclusion) {
  59628. this._defines.PARALLAXOCCLUSION = true;
  59629. }
  59630. }
  59631. if (this.invertNormalMapX) {
  59632. this._defines.INVERTNORMALMAPX = true;
  59633. }
  59634. if (this.invertNormalMapY) {
  59635. this._defines.INVERTNORMALMAPY = true;
  59636. }
  59637. if (scene._mirroredCameraPosition) {
  59638. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  59639. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  59640. }
  59641. }
  59642. }
  59643. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  59644. if (!this.refractionTexture.isReady()) {
  59645. return false;
  59646. }
  59647. else {
  59648. needUVs = true;
  59649. this._defines.REFRACTION = true;
  59650. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  59651. if (this.linkRefractionWithTransparency) {
  59652. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  59653. }
  59654. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  59655. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  59656. if (this.refractionTexture.isPMREM) {
  59657. this._defines.USEPMREMREFRACTION = true;
  59658. }
  59659. }
  59660. }
  59661. }
  59662. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  59663. if (!this.cameraColorGradingTexture.isReady()) {
  59664. return false;
  59665. }
  59666. else {
  59667. this._defines.CAMERACOLORGRADING = true;
  59668. }
  59669. }
  59670. if (!this.backFaceCulling && this.twoSidedLighting) {
  59671. this._defines.TWOSIDEDLIGHTING = true;
  59672. }
  59673. }
  59674. // Effect
  59675. if (scene.clipPlane) {
  59676. this._defines.CLIPPLANE = true;
  59677. }
  59678. if (engine.getAlphaTesting()) {
  59679. this._defines.ALPHATEST = true;
  59680. }
  59681. if (this._shouldUseAlphaFromAlbedoTexture()) {
  59682. this._defines.ALPHAFROMALBEDO = true;
  59683. }
  59684. if (this.useEmissiveAsIllumination) {
  59685. this._defines.EMISSIVEASILLUMINATION = true;
  59686. }
  59687. if (this.linkEmissiveWithAlbedo) {
  59688. this._defines.LINKEMISSIVEWITHALBEDO = true;
  59689. }
  59690. if (this.useLogarithmicDepth) {
  59691. this._defines.LOGARITHMICDEPTH = true;
  59692. }
  59693. if (this.cameraContrast != 1) {
  59694. this._defines.CAMERACONTRAST = true;
  59695. }
  59696. if (this.cameraExposure != 1) {
  59697. this._defines.CAMERATONEMAP = true;
  59698. }
  59699. if (this.cameraColorCurves) {
  59700. this._defines.CAMERACOLORCURVES = true;
  59701. }
  59702. if (this.overloadedShadeIntensity != 1 ||
  59703. this.overloadedShadowIntensity != 1) {
  59704. this._defines.OVERLOADEDSHADOWVALUES = true;
  59705. }
  59706. if (this.overloadedMicroSurfaceIntensity > 0 ||
  59707. this.overloadedEmissiveIntensity > 0 ||
  59708. this.overloadedReflectivityIntensity > 0 ||
  59709. this.overloadedAlbedoIntensity > 0 ||
  59710. this.overloadedAmbientIntensity > 0 ||
  59711. this.overloadedReflectionIntensity > 0) {
  59712. this._defines.OVERLOADEDVALUES = true;
  59713. }
  59714. // Point size
  59715. if (this.pointsCloud || scene.forcePointsCloud) {
  59716. this._defines.POINTSIZE = true;
  59717. }
  59718. // Fog
  59719. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  59720. this._defines.FOG = true;
  59721. }
  59722. if (BABYLON.StandardMaterial.FresnelEnabled) {
  59723. // Fresnel
  59724. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  59725. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  59726. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  59727. this._defines.OPACITYFRESNEL = true;
  59728. }
  59729. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  59730. this._defines.EMISSIVEFRESNEL = true;
  59731. }
  59732. needNormals = true;
  59733. this._defines.FRESNEL = true;
  59734. }
  59735. }
  59736. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  59737. this._defines.SPECULAROVERALPHA = true;
  59738. }
  59739. if (this.usePhysicalLightFalloff) {
  59740. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  59741. }
  59742. if (this.useRadianceOverAlpha) {
  59743. this._defines.RADIANCEOVERALPHA = true;
  59744. }
  59745. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  59746. this._defines.METALLICWORKFLOW = true;
  59747. }
  59748. // Attribs
  59749. if (mesh) {
  59750. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  59751. this._defines.NORMAL = true;
  59752. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  59753. this._defines.TANGENT = true;
  59754. }
  59755. }
  59756. if (needUVs) {
  59757. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59758. this._defines.UV1 = true;
  59759. }
  59760. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59761. this._defines.UV2 = true;
  59762. }
  59763. }
  59764. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59765. this._defines.VERTEXCOLOR = true;
  59766. if (mesh.hasVertexAlpha) {
  59767. this._defines.VERTEXALPHA = true;
  59768. }
  59769. }
  59770. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59771. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  59772. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  59773. }
  59774. // Instances
  59775. if (useInstances) {
  59776. this._defines.INSTANCES = true;
  59777. }
  59778. }
  59779. // Get correct effect
  59780. if (!this._defines.isEqual(this._cachedDefines)) {
  59781. this._defines.cloneTo(this._cachedDefines);
  59782. scene.resetCachedMaterial();
  59783. // Fallbacks
  59784. var fallbacks = new BABYLON.EffectFallbacks();
  59785. if (this._defines.REFLECTION) {
  59786. fallbacks.addFallback(0, "REFLECTION");
  59787. }
  59788. if (this._defines.REFRACTION) {
  59789. fallbacks.addFallback(0, "REFRACTION");
  59790. }
  59791. if (this._defines.REFLECTIVITY) {
  59792. fallbacks.addFallback(0, "REFLECTIVITY");
  59793. }
  59794. if (this._defines.BUMP) {
  59795. fallbacks.addFallback(0, "BUMP");
  59796. }
  59797. if (this._defines.PARALLAX) {
  59798. fallbacks.addFallback(1, "PARALLAX");
  59799. }
  59800. if (this._defines.PARALLAXOCCLUSION) {
  59801. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  59802. }
  59803. if (this._defines.SPECULAROVERALPHA) {
  59804. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  59805. }
  59806. if (this._defines.FOG) {
  59807. fallbacks.addFallback(1, "FOG");
  59808. }
  59809. if (this._defines.POINTSIZE) {
  59810. fallbacks.addFallback(0, "POINTSIZE");
  59811. }
  59812. if (this._defines.LOGARITHMICDEPTH) {
  59813. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  59814. }
  59815. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  59816. if (this._defines.SPECULARTERM) {
  59817. fallbacks.addFallback(0, "SPECULARTERM");
  59818. }
  59819. if (this._defines.OPACITYFRESNEL) {
  59820. fallbacks.addFallback(1, "OPACITYFRESNEL");
  59821. }
  59822. if (this._defines.EMISSIVEFRESNEL) {
  59823. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  59824. }
  59825. if (this._defines.FRESNEL) {
  59826. fallbacks.addFallback(3, "FRESNEL");
  59827. }
  59828. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  59829. fallbacks.addCPUSkinningFallback(0, mesh);
  59830. }
  59831. //Attributes
  59832. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59833. if (this._defines.NORMAL) {
  59834. attribs.push(BABYLON.VertexBuffer.NormalKind);
  59835. }
  59836. if (this._defines.TANGENT) {
  59837. attribs.push(BABYLON.VertexBuffer.TangentKind);
  59838. }
  59839. if (this._defines.UV1) {
  59840. attribs.push(BABYLON.VertexBuffer.UVKind);
  59841. }
  59842. if (this._defines.UV2) {
  59843. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59844. }
  59845. if (this._defines.VERTEXCOLOR) {
  59846. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59847. }
  59848. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  59849. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  59850. // Legacy browser patch
  59851. var join = this._defines.toString();
  59852. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  59853. "vFogInfos", "vFogColor", "pointSize",
  59854. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  59855. "mBones",
  59856. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  59857. "depthValues",
  59858. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  59859. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  59860. "logarithmicDepthConstant",
  59861. "vSphericalX", "vSphericalY", "vSphericalZ",
  59862. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  59863. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  59864. "vMicrosurfaceTextureLods",
  59865. "vCameraInfos"
  59866. ];
  59867. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  59868. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  59869. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  59870. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  59871. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  59872. }
  59873. if (!this._effect.isReady()) {
  59874. return false;
  59875. }
  59876. this._renderId = scene.getRenderId();
  59877. this._wasPreviouslyReady = true;
  59878. return true;
  59879. };
  59880. PBRMaterial.prototype.unbind = function () {
  59881. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  59882. this._effect.setTexture("reflection2DSampler", null);
  59883. }
  59884. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  59885. this._effect.setTexture("refraction2DSampler", null);
  59886. }
  59887. _super.prototype.unbind.call(this);
  59888. };
  59889. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59890. this._effect.setMatrix("world", world);
  59891. };
  59892. PBRMaterial.prototype.bind = function (world, mesh) {
  59893. this._myScene = this.getScene();
  59894. // Matrices
  59895. this.bindOnlyWorldMatrix(world);
  59896. // Bones
  59897. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59898. if (this._myScene.getCachedMaterial() !== this) {
  59899. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  59900. if (BABYLON.StandardMaterial.FresnelEnabled) {
  59901. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  59902. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  59903. }
  59904. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  59905. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  59906. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  59907. }
  59908. }
  59909. // Textures
  59910. if (this._myScene.texturesEnabled) {
  59911. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  59912. this._effect.setTexture("albedoSampler", this.albedoTexture);
  59913. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  59914. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  59915. }
  59916. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  59917. this._effect.setTexture("ambientSampler", this.ambientTexture);
  59918. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  59919. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  59920. }
  59921. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  59922. this._effect.setTexture("opacitySampler", this.opacityTexture);
  59923. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  59924. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  59925. }
  59926. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  59927. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  59928. if (this.reflectionTexture.isCube) {
  59929. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  59930. }
  59931. else {
  59932. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  59933. }
  59934. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  59935. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  59936. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  59937. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  59938. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  59939. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  59940. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  59941. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  59942. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  59943. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  59944. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  59945. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  59946. }
  59947. }
  59948. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  59949. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  59950. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  59951. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  59952. }
  59953. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  59954. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  59955. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  59956. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  59957. }
  59958. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  59959. if (this.metallicTexture) {
  59960. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  59961. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  59962. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  59963. }
  59964. else if (this.reflectivityTexture) {
  59965. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  59966. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  59967. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  59968. }
  59969. }
  59970. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  59971. this._effect.setTexture("bumpSampler", this.bumpTexture);
  59972. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  59973. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  59974. }
  59975. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  59976. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  59977. var depth = 1.0;
  59978. if (this.refractionTexture.isCube) {
  59979. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  59980. }
  59981. else {
  59982. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  59983. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  59984. if (this.refractionTexture.depth) {
  59985. depth = this.refractionTexture.depth;
  59986. }
  59987. }
  59988. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  59989. }
  59990. if ((this.reflectionTexture || this.refractionTexture)) {
  59991. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  59992. }
  59993. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  59994. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  59995. }
  59996. }
  59997. // Clip plane
  59998. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  59999. // Point size
  60000. if (this.pointsCloud) {
  60001. this._effect.setFloat("pointSize", this.pointSize);
  60002. }
  60003. // Colors
  60004. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  60005. if (this._defines.METALLICWORKFLOW) {
  60006. PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
  60007. PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
  60008. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  60009. }
  60010. else {
  60011. // GAMMA CORRECTION.
  60012. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  60013. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  60014. }
  60015. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  60016. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  60017. // GAMMA CORRECTION.
  60018. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  60019. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  60020. // GAMMA CORRECTION.
  60021. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  60022. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  60023. }
  60024. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  60025. // GAMMA CORRECTION.
  60026. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  60027. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  60028. // Lights
  60029. if (this._myScene.lightsEnabled && !this.disableLighting) {
  60030. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  60031. }
  60032. // View
  60033. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  60034. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  60035. }
  60036. // Fog
  60037. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  60038. this._lightingInfos.x = this.directIntensity;
  60039. this._lightingInfos.y = this.emissiveIntensity;
  60040. this._lightingInfos.z = this.environmentIntensity;
  60041. this._lightingInfos.w = this.specularIntensity;
  60042. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  60043. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  60044. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  60045. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  60046. this._cameraInfos.x = this.cameraExposure;
  60047. this._cameraInfos.y = this.cameraContrast;
  60048. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  60049. if (this.cameraColorCurves) {
  60050. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  60051. }
  60052. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  60053. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  60054. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  60055. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  60056. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  60057. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  60058. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  60059. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  60060. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  60061. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  60062. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  60063. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  60064. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  60065. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  60066. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  60067. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  60068. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  60069. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  60070. // Log. depth
  60071. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  60072. }
  60073. this._afterBind(mesh);
  60074. this._myScene = null;
  60075. };
  60076. PBRMaterial.prototype.getAnimatables = function () {
  60077. var results = [];
  60078. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  60079. results.push(this.albedoTexture);
  60080. }
  60081. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  60082. results.push(this.ambientTexture);
  60083. }
  60084. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  60085. results.push(this.opacityTexture);
  60086. }
  60087. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  60088. results.push(this.reflectionTexture);
  60089. }
  60090. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  60091. results.push(this.emissiveTexture);
  60092. }
  60093. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  60094. results.push(this.metallicTexture);
  60095. }
  60096. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  60097. results.push(this.reflectivityTexture);
  60098. }
  60099. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  60100. results.push(this.bumpTexture);
  60101. }
  60102. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  60103. results.push(this.lightmapTexture);
  60104. }
  60105. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  60106. results.push(this.refractionTexture);
  60107. }
  60108. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  60109. results.push(this.cameraColorGradingTexture);
  60110. }
  60111. return results;
  60112. };
  60113. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60114. if (forceDisposeTextures) {
  60115. if (this.albedoTexture) {
  60116. this.albedoTexture.dispose();
  60117. }
  60118. if (this.ambientTexture) {
  60119. this.ambientTexture.dispose();
  60120. }
  60121. if (this.opacityTexture) {
  60122. this.opacityTexture.dispose();
  60123. }
  60124. if (this.reflectionTexture) {
  60125. this.reflectionTexture.dispose();
  60126. }
  60127. if (this.emissiveTexture) {
  60128. this.emissiveTexture.dispose();
  60129. }
  60130. if (this.metallicTexture) {
  60131. this.metallicTexture.dispose();
  60132. }
  60133. if (this.reflectivityTexture) {
  60134. this.reflectivityTexture.dispose();
  60135. }
  60136. if (this.bumpTexture) {
  60137. this.bumpTexture.dispose();
  60138. }
  60139. if (this.lightmapTexture) {
  60140. this.lightmapTexture.dispose();
  60141. }
  60142. if (this.refractionTexture) {
  60143. this.refractionTexture.dispose();
  60144. }
  60145. if (this.cameraColorGradingTexture) {
  60146. this.cameraColorGradingTexture.dispose();
  60147. }
  60148. }
  60149. this._renderTargets.dispose();
  60150. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60151. };
  60152. PBRMaterial.prototype.clone = function (name) {
  60153. var _this = this;
  60154. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  60155. };
  60156. PBRMaterial.prototype.serialize = function () {
  60157. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60158. serializationObject.customType = "BABYLON.PBRMaterial";
  60159. return serializationObject;
  60160. };
  60161. // Statics
  60162. PBRMaterial.Parse = function (source, scene, rootUrl) {
  60163. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  60164. };
  60165. return PBRMaterial;
  60166. }(BABYLON.Material));
  60167. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  60168. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  60169. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  60170. PBRMaterial._scaledReflection = new BABYLON.Color3();
  60171. __decorate([
  60172. BABYLON.serialize()
  60173. ], PBRMaterial.prototype, "directIntensity", void 0);
  60174. __decorate([
  60175. BABYLON.serialize()
  60176. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  60177. __decorate([
  60178. BABYLON.serialize()
  60179. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  60180. __decorate([
  60181. BABYLON.serialize()
  60182. ], PBRMaterial.prototype, "specularIntensity", void 0);
  60183. __decorate([
  60184. BABYLON.serialize()
  60185. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  60186. __decorate([
  60187. BABYLON.serialize()
  60188. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  60189. __decorate([
  60190. BABYLON.serialize()
  60191. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  60192. __decorate([
  60193. BABYLON.serialize()
  60194. ], PBRMaterial.prototype, "cameraExposure", void 0);
  60195. __decorate([
  60196. BABYLON.serialize()
  60197. ], PBRMaterial.prototype, "cameraContrast", void 0);
  60198. __decorate([
  60199. BABYLON.serializeAsTexture()
  60200. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  60201. __decorate([
  60202. BABYLON.serializeAsColorCurves()
  60203. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  60204. __decorate([
  60205. BABYLON.serializeAsColor3()
  60206. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  60207. __decorate([
  60208. BABYLON.serialize()
  60209. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  60210. __decorate([
  60211. BABYLON.serializeAsColor3()
  60212. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  60213. __decorate([
  60214. BABYLON.serialize()
  60215. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  60216. __decorate([
  60217. BABYLON.serializeAsColor3()
  60218. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  60219. __decorate([
  60220. BABYLON.serialize()
  60221. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  60222. __decorate([
  60223. BABYLON.serializeAsColor3()
  60224. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  60225. __decorate([
  60226. BABYLON.serialize()
  60227. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  60228. __decorate([
  60229. BABYLON.serializeAsColor3()
  60230. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  60231. __decorate([
  60232. BABYLON.serialize()
  60233. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  60234. __decorate([
  60235. BABYLON.serialize()
  60236. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  60237. __decorate([
  60238. BABYLON.serialize()
  60239. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  60240. __decorate([
  60241. BABYLON.serializeAsTexture()
  60242. ], PBRMaterial.prototype, "albedoTexture", void 0);
  60243. __decorate([
  60244. BABYLON.serializeAsTexture()
  60245. ], PBRMaterial.prototype, "ambientTexture", void 0);
  60246. __decorate([
  60247. BABYLON.serialize()
  60248. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  60249. __decorate([
  60250. BABYLON.serializeAsTexture()
  60251. ], PBRMaterial.prototype, "opacityTexture", void 0);
  60252. __decorate([
  60253. BABYLON.serializeAsTexture()
  60254. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  60255. __decorate([
  60256. BABYLON.serializeAsTexture()
  60257. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  60258. __decorate([
  60259. BABYLON.serializeAsTexture()
  60260. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  60261. __decorate([
  60262. BABYLON.serializeAsTexture()
  60263. ], PBRMaterial.prototype, "metallicTexture", void 0);
  60264. __decorate([
  60265. BABYLON.serialize()
  60266. ], PBRMaterial.prototype, "metallic", void 0);
  60267. __decorate([
  60268. BABYLON.serialize()
  60269. ], PBRMaterial.prototype, "roughness", void 0);
  60270. __decorate([
  60271. BABYLON.serializeAsTexture()
  60272. ], PBRMaterial.prototype, "bumpTexture", void 0);
  60273. __decorate([
  60274. BABYLON.serializeAsTexture()
  60275. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  60276. __decorate([
  60277. BABYLON.serializeAsTexture()
  60278. ], PBRMaterial.prototype, "refractionTexture", void 0);
  60279. __decorate([
  60280. BABYLON.serializeAsColor3("ambient")
  60281. ], PBRMaterial.prototype, "ambientColor", void 0);
  60282. __decorate([
  60283. BABYLON.serializeAsColor3("albedo")
  60284. ], PBRMaterial.prototype, "albedoColor", void 0);
  60285. __decorate([
  60286. BABYLON.serializeAsColor3("reflectivity")
  60287. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  60288. __decorate([
  60289. BABYLON.serializeAsColor3("reflection")
  60290. ], PBRMaterial.prototype, "reflectionColor", void 0);
  60291. __decorate([
  60292. BABYLON.serializeAsColor3("emissive")
  60293. ], PBRMaterial.prototype, "emissiveColor", void 0);
  60294. __decorate([
  60295. BABYLON.serialize()
  60296. ], PBRMaterial.prototype, "microSurface", void 0);
  60297. __decorate([
  60298. BABYLON.serialize()
  60299. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  60300. __decorate([
  60301. BABYLON.serialize()
  60302. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  60303. __decorate([
  60304. BABYLON.serializeAsFresnelParameters()
  60305. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  60306. __decorate([
  60307. BABYLON.serializeAsFresnelParameters()
  60308. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  60309. __decorate([
  60310. BABYLON.serialize()
  60311. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  60312. __decorate([
  60313. BABYLON.serialize()
  60314. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  60315. __decorate([
  60316. BABYLON.serialize()
  60317. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  60318. __decorate([
  60319. BABYLON.serialize()
  60320. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  60321. __decorate([
  60322. BABYLON.serialize()
  60323. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  60324. __decorate([
  60325. BABYLON.serialize()
  60326. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  60327. __decorate([
  60328. BABYLON.serialize()
  60329. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  60330. __decorate([
  60331. BABYLON.serialize()
  60332. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  60333. __decorate([
  60334. BABYLON.serialize()
  60335. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  60336. __decorate([
  60337. BABYLON.serialize()
  60338. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  60339. __decorate([
  60340. BABYLON.serialize()
  60341. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  60342. __decorate([
  60343. BABYLON.serialize()
  60344. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  60345. __decorate([
  60346. BABYLON.serialize()
  60347. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  60348. __decorate([
  60349. BABYLON.serialize()
  60350. ], PBRMaterial.prototype, "useParallax", void 0);
  60351. __decorate([
  60352. BABYLON.serialize()
  60353. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  60354. __decorate([
  60355. BABYLON.serialize()
  60356. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  60357. __decorate([
  60358. BABYLON.serialize()
  60359. ], PBRMaterial.prototype, "disableLighting", void 0);
  60360. __decorate([
  60361. BABYLON.serialize()
  60362. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  60363. __decorate([
  60364. BABYLON.serialize()
  60365. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  60366. __decorate([
  60367. BABYLON.serialize()
  60368. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  60369. __decorate([
  60370. BABYLON.serialize()
  60371. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  60372. __decorate([
  60373. BABYLON.serialize()
  60374. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  60375. BABYLON.PBRMaterial = PBRMaterial;
  60376. })(BABYLON || (BABYLON = {}));
  60377. //# sourceMappingURL=babylon.pbrMaterial.js.map
  60378. var BABYLON;
  60379. (function (BABYLON) {
  60380. var DebugLayer = (function () {
  60381. function DebugLayer(scene) {
  60382. this._scene = scene;
  60383. }
  60384. /** Creates the inspector window. */
  60385. DebugLayer.prototype._createInspector = function (config) {
  60386. if (config === void 0) { config = {}; }
  60387. var popup = config.popup || false;
  60388. var initialTab = config.initialTab || 0;
  60389. var parentElement = config.parentElement || null;
  60390. if (!this._inspector) {
  60391. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  60392. } // else nothing to do,; instance is already existing
  60393. };
  60394. DebugLayer.prototype.isVisible = function () {
  60395. if (!this._inspector) {
  60396. return false;
  60397. }
  60398. return true;
  60399. };
  60400. DebugLayer.prototype.hide = function () {
  60401. if (this._inspector) {
  60402. this._inspector.dispose();
  60403. this._inspector = null;
  60404. }
  60405. };
  60406. DebugLayer.prototype.show = function (config) {
  60407. if (config === void 0) { config = {}; }
  60408. if (typeof INSPECTOR == 'undefined') {
  60409. // Load inspector and add it to the DOM
  60410. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  60411. }
  60412. else {
  60413. // Otherwise creates the inspector
  60414. this._createInspector(config);
  60415. }
  60416. };
  60417. return DebugLayer;
  60418. }());
  60419. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  60420. BABYLON.DebugLayer = DebugLayer;
  60421. })(BABYLON || (BABYLON = {}));
  60422. //# sourceMappingURL=babylon.debugLayer.js.map
  60423. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  60424. var BABYLON;
  60425. (function (BABYLON) {
  60426. var StandardRenderingPipeline = (function (_super) {
  60427. __extends(StandardRenderingPipeline, _super);
  60428. /**
  60429. * @constructor
  60430. * @param {string} name - The rendering pipeline name
  60431. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60432. * @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)
  60433. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  60434. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60435. */
  60436. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  60437. if (originalPostProcess === void 0) { originalPostProcess = null; }
  60438. var _this = _super.call(this, scene.getEngine(), name) || this;
  60439. _this.downSampleX4PostProcess = null;
  60440. _this.brightPassPostProcess = null;
  60441. _this.gaussianBlurHPostProcesses = [];
  60442. _this.gaussianBlurVPostProcesses = [];
  60443. _this.textureAdderPostProcess = null;
  60444. _this.textureAdderFinalPostProcess = null;
  60445. _this.lensFlareFinalPostProcess = null;
  60446. _this.lensFlarePostProcess = null;
  60447. _this.lensFlareComposePostProcess = null;
  60448. _this.depthOfFieldPostProcess = null;
  60449. // Values
  60450. _this.brightThreshold = 1.0;
  60451. _this.blurWidth = 2.0;
  60452. _this.horizontalBlur = false;
  60453. _this.gaussianCoefficient = 0.25;
  60454. _this.gaussianMean = 1.0;
  60455. _this.gaussianStandardDeviation = 1.0;
  60456. _this.exposure = 1.0;
  60457. _this.lensTexture = null;
  60458. _this.lensColorTexture = null;
  60459. _this.lensFlareStrength = 20.0;
  60460. _this.lensFlareGhostDispersal = 1.4;
  60461. _this.lensFlareHaloWidth = 0.7;
  60462. _this.lensFlareDistortionStrength = 16.0;
  60463. _this.lensStarTexture = null;
  60464. _this.lensFlareDirtTexture = null;
  60465. _this.depthOfFieldDistance = 10.0;
  60466. _this.depthOfFieldBlurWidth = 2.0;
  60467. // IAnimatable
  60468. _this.animations = [];
  60469. _this._depthRenderer = null;
  60470. _this._currentDepthOfFieldSource = null;
  60471. // Getters and setters
  60472. _this._depthOfFieldEnabled = true;
  60473. _this._lensFlareEnabled = true;
  60474. // Initialize
  60475. _this._scene = scene;
  60476. // Create pass post-processe
  60477. if (!originalPostProcess) {
  60478. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  60479. }
  60480. else {
  60481. _this.originalPostProcess = originalPostProcess;
  60482. }
  60483. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  60484. // Create down sample X4 post-process
  60485. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  60486. // Create bright pass post-process
  60487. _this._createBrightPassPostProcess(scene, ratio / 2);
  60488. // Create gaussian blur post-processes (down sampling blurs)
  60489. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  60490. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  60491. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  60492. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  60493. // Create texture adder post-process
  60494. _this._createTextureAdderPostProcess(scene, ratio);
  60495. // Create depth-of-field source post-process
  60496. _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);
  60497. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  60498. // Create lens flare post-process
  60499. _this._createLensFlarePostProcess(scene, ratio);
  60500. // Create depth-of-field source post-process post lens-flare and disable it now
  60501. _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);
  60502. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  60503. // Create gaussian blur used by depth-of-field
  60504. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  60505. // Create depth-of-field post-process
  60506. _this._createDepthOfFieldPostProcess(scene, ratio);
  60507. // Finish
  60508. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60509. if (cameras !== null) {
  60510. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60511. }
  60512. // Deactivate
  60513. _this.LensFlareEnabled = false;
  60514. _this.DepthOfFieldEnabled = false;
  60515. return _this;
  60516. }
  60517. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  60518. get: function () {
  60519. return this._depthOfFieldEnabled;
  60520. },
  60521. set: function (enabled) {
  60522. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  60523. if (enabled && !this._depthOfFieldEnabled) {
  60524. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  60525. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  60526. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  60527. this._depthRenderer = this._scene.enableDepthRenderer();
  60528. }
  60529. else if (!enabled && this._depthOfFieldEnabled) {
  60530. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  60531. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  60532. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  60533. }
  60534. this._depthOfFieldEnabled = enabled;
  60535. },
  60536. enumerable: true,
  60537. configurable: true
  60538. });
  60539. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  60540. get: function () {
  60541. return this._lensFlareEnabled;
  60542. },
  60543. set: function (enabled) {
  60544. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  60545. if (enabled && !this._lensFlareEnabled) {
  60546. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  60547. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  60548. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  60549. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  60550. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  60551. this._setDepthOfFieldSavePostProcess("HDRPostLensFlareDepthOfFieldSource");
  60552. }
  60553. else if (!enabled && this._lensFlareEnabled) {
  60554. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  60555. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  60556. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  60557. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  60558. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  60559. this._setDepthOfFieldSavePostProcess("HDRBaseDepthOfFieldSource");
  60560. }
  60561. this._lensFlareEnabled = enabled;
  60562. },
  60563. enumerable: true,
  60564. configurable: true
  60565. });
  60566. // Sets depth-of-field save post-process
  60567. StandardRenderingPipeline.prototype._setDepthOfFieldSavePostProcess = function (name) {
  60568. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  60569. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, name, this._scene.cameras);
  60570. switch (name) {
  60571. case "HDRBaseDepthOfFieldSource":
  60572. this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess;
  60573. break;
  60574. case "HDRPostLensFlareDepthOfFieldSource":
  60575. this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess;
  60576. break;
  60577. default: break;
  60578. }
  60579. };
  60580. // Down Sample X4 Post-Processs
  60581. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  60582. var _this = this;
  60583. var downSampleX4Offsets = new Array(32);
  60584. 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);
  60585. this.downSampleX4PostProcess.onApply = function (effect) {
  60586. var id = 0;
  60587. for (var i = -2; i < 2; i++) {
  60588. for (var j = -2; j < 2; j++) {
  60589. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  60590. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  60591. id += 2;
  60592. }
  60593. }
  60594. effect.setArray2("dsOffsets", downSampleX4Offsets);
  60595. };
  60596. // Add to pipeline
  60597. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  60598. };
  60599. // Brightpass Post-Process
  60600. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  60601. var _this = this;
  60602. var brightOffsets = new Array(8);
  60603. 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);
  60604. this.brightPassPostProcess.onApply = function (effect) {
  60605. var sU = (1.0 / _this.brightPassPostProcess.width);
  60606. var sV = (1.0 / _this.brightPassPostProcess.height);
  60607. brightOffsets[0] = -0.5 * sU;
  60608. brightOffsets[1] = 0.5 * sV;
  60609. brightOffsets[2] = 0.5 * sU;
  60610. brightOffsets[3] = 0.5 * sV;
  60611. brightOffsets[4] = -0.5 * sU;
  60612. brightOffsets[5] = -0.5 * sV;
  60613. brightOffsets[6] = 0.5 * sU;
  60614. brightOffsets[7] = -0.5 * sV;
  60615. effect.setArray2("dsOffsets", brightOffsets);
  60616. effect.setFloat("brightThreshold", _this.brightThreshold);
  60617. };
  60618. // Add to pipeline
  60619. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  60620. };
  60621. // Create gaussian blur H&V post-processes
  60622. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  60623. var _this = this;
  60624. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  60625. var blurOffsets = new Array(9);
  60626. var blurWeights = new Array(9);
  60627. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  60628. var callback = function (height) {
  60629. return function (effect) {
  60630. // Weights
  60631. var x = 0.0;
  60632. for (var i = 0; i < 9; i++) {
  60633. x = (i - 4.0) / 4.0;
  60634. blurWeights[i] =
  60635. _this.gaussianCoefficient
  60636. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  60637. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  60638. }
  60639. var lastOutputDimensions = {
  60640. width: scene.getEngine().getRenderWidth(),
  60641. height: scene.getEngine().getRenderHeight()
  60642. };
  60643. for (var i = 0; i < 9; i++) {
  60644. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  60645. blurOffsets[i] = value;
  60646. }
  60647. effect.setArray("blurOffsets", blurOffsets);
  60648. effect.setArray("blurWeights", blurWeights);
  60649. if (height) {
  60650. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  60651. }
  60652. else {
  60653. effect.setFloat("blurWidth", _this[blurWidthKey]);
  60654. }
  60655. };
  60656. };
  60657. // Create horizontal gaussian blur post-processes
  60658. 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);
  60659. gaussianBlurHPostProcess.onApply = callback(false);
  60660. // Create vertical gaussian blur post-process
  60661. 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);
  60662. gaussianBlurVPostProcess.onApply = callback(true);
  60663. // Add to pipeline
  60664. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  60665. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  60666. // Finish
  60667. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  60668. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  60669. };
  60670. // Create texture adder post-process
  60671. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  60672. var _this = this;
  60673. 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);
  60674. this.textureAdderPostProcess.onApply = function (effect) {
  60675. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  60676. effect.setTexture("lensSampler", _this.lensTexture);
  60677. effect.setFloat("exposure", _this.exposure);
  60678. };
  60679. // Add to pipeline
  60680. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  60681. };
  60682. // Create lens flare post-process
  60683. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  60684. var _this = this;
  60685. 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);
  60686. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  60687. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  60688. 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);
  60689. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  60690. var resolution = new BABYLON.Vector2(0, 0);
  60691. // Lens flare
  60692. this.lensFlarePostProcess.onApply = function (effect) {
  60693. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  60694. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  60695. effect.setFloat("strength", _this.lensFlareStrength);
  60696. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  60697. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  60698. // Shift
  60699. resolution.x = _this.lensFlarePostProcess.width;
  60700. resolution.y = _this.lensFlarePostProcess.height;
  60701. effect.setVector2("resolution", resolution);
  60702. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  60703. };
  60704. // Compose
  60705. 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);
  60706. 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);
  60707. this.lensFlareComposePostProcess.onApply = function (effect) {
  60708. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  60709. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  60710. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  60711. // Lens start rotation matrix
  60712. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  60713. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  60714. 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));
  60715. camRot *= 4.0;
  60716. 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);
  60717. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  60718. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  60719. };
  60720. };
  60721. // Create depth-of-field post-process
  60722. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  60723. var _this = this;
  60724. 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);
  60725. this.depthOfFieldPostProcess.onApply = function (effect) {
  60726. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  60727. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  60728. effect.setFloat("distance", _this.depthOfFieldDistance);
  60729. };
  60730. // Add to pipeline
  60731. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  60732. };
  60733. // Dispose
  60734. StandardRenderingPipeline.prototype.dispose = function () {
  60735. for (var i = 0; i < this._scene.cameras.length; i++) {
  60736. var camera = this._scene.cameras[i];
  60737. this.originalPostProcess.dispose(camera);
  60738. this.downSampleX4PostProcess.dispose(camera);
  60739. this.brightPassPostProcess.dispose(camera);
  60740. this.textureAdderPostProcess.dispose(camera);
  60741. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  60742. this.gaussianBlurHPostProcesses[j].dispose(camera);
  60743. }
  60744. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  60745. this.gaussianBlurVPostProcesses[j].dispose(camera);
  60746. }
  60747. this.textureAdderFinalPostProcess.dispose(camera);
  60748. this.lensFlarePostProcess.dispose(camera);
  60749. this.lensFlareComposePostProcess.dispose(camera);
  60750. this.depthOfFieldPostProcess.dispose(camera);
  60751. }
  60752. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60753. _super.prototype.dispose.call(this);
  60754. };
  60755. // Serialize rendering pipeline
  60756. StandardRenderingPipeline.prototype.serialize = function () {
  60757. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60758. serializationObject.customType = "StandardRenderingPipeline";
  60759. return serializationObject;
  60760. };
  60761. // Parse serialized pipeline
  60762. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  60763. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  60764. };
  60765. return StandardRenderingPipeline;
  60766. }(BABYLON.PostProcessRenderPipeline));
  60767. __decorate([
  60768. BABYLON.serialize()
  60769. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  60770. __decorate([
  60771. BABYLON.serialize()
  60772. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  60773. __decorate([
  60774. BABYLON.serialize()
  60775. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  60776. __decorate([
  60777. BABYLON.serialize()
  60778. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  60779. __decorate([
  60780. BABYLON.serialize()
  60781. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  60782. __decorate([
  60783. BABYLON.serialize()
  60784. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  60785. __decorate([
  60786. BABYLON.serialize()
  60787. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  60788. __decorate([
  60789. BABYLON.serializeAsTexture("lensTexture")
  60790. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  60791. __decorate([
  60792. BABYLON.serializeAsTexture("lensColorTexture")
  60793. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  60794. __decorate([
  60795. BABYLON.serialize()
  60796. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  60797. __decorate([
  60798. BABYLON.serialize()
  60799. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  60800. __decorate([
  60801. BABYLON.serialize()
  60802. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  60803. __decorate([
  60804. BABYLON.serialize()
  60805. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  60806. __decorate([
  60807. BABYLON.serializeAsTexture("lensStarTexture")
  60808. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  60809. __decorate([
  60810. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  60811. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  60812. __decorate([
  60813. BABYLON.serialize()
  60814. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  60815. __decorate([
  60816. BABYLON.serialize()
  60817. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  60818. __decorate([
  60819. BABYLON.serialize()
  60820. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  60821. __decorate([
  60822. BABYLON.serialize()
  60823. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  60824. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  60825. })(BABYLON || (BABYLON = {}));
  60826. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  60827. 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#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_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#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\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#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_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#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_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#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_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#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\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#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_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#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_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}"};
  60828. 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#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_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;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\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,float depthScale)\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\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample-darkness,0.,1.); \n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,esm,vOverloadedShadowIntensity.x);\n#else\nreturn esm;\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"};
  60829. 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))<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),(n=t.Vector3.Dot(this._tempVector4,r))>=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)>=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)>=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){if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,.01);for(var t,s=this._collisionCache.getMeshes(),l=Object.keys(s),n=l.length,a=0;a<n;++a)if(t=l[a],parseInt(t)!=r){var c=s[t];c.checkCollisions&&this.checkCollision(c)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=.01?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);o.Matrix.FromArray(e.worldMatrixFromCache).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),new i(t,this._collisionCache,r).collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var s={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},l={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:s};postMessage(l,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){return new r(t.r+(i.r-t.r)*n,t.g+(i.g-t.g)*n,t.b+(i.b-t.b)*n)},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;return new r(.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),.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))},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;return new r(t.x*a+n.x*u+i.x*m+o.x*y,t.y*a+n.y*u+i.y*m+o.y*y)},r.Lerp=function(t,i,n){return new r(t.x+(i.x-t.x)*n,t.y+(i.y-t.y)*n)},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){return new r(t.x<i.x?t.x:i.x,t.y<i.y?t.y:i.y)},r.Maximize=function(t,i){return new r(t.x>i.x?t.x:i.x,t.y>i.y?t.y:i.y)},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;return e/(e-(r.Dot(i,n)-o))},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;return new r(.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),.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),.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))},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;return new r(t.x*a+n.x*u+i.x*m+o.x*y,t.y*a+n.y*u+i.y*m+o.y*y,t.z*a+n.z*u+i.z*m+o.z*y)},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){M.Vector3[0].x=t.y*i.z-t.z*i.y,M.Vector3[0].y=t.z*i.x-t.x*i.z,M.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(M.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=M.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){return new t(this.width+i.width,this.height+i.height)},t.prototype.subtract=function(i){return new t(this.width-i.width,this.height-i.height)},t.Lerp=function(i,r,n){return new t(i.width+(r.width-i.width)*n,i.height+(r.height-i.height)*n)},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(){return new i(-this.x,-this.y,-this.z,this.w)},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;return m<-.4999999?(t.y=2*Math.atan2(o,e),t.x=Math.PI/2,t.z=0):m>.4999999?(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=M.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,t.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,\nt.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,M.Matrix[0]),a.FromRotationMatrixToRef(M.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,M.Matrix[1]),i.toRotationMatrix(M.Matrix[0]),M.Matrix[1].multiplyToRef(M.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;return new t(n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15])},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){return e.Dot(this.normal,t)<=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;!function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\",t[t.BONE=2]=\"BONE\"}(t.Space||(t.Space={}));var p=function(){function t(){}return t}();p.X=new e(1,0,0),p.Y=new e(0,1,0),p.Z=new e(0,0,1),t.Axis=p;var f=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;a-=(e*(m*a)+s*m+h*a-t)*(1/(3*e*m+2*s*a+h)),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=f;var x;!function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(x=t.Orientation||(t.Orientation={}));var l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,r){var n=r.subtract(i);return new t(Math.atan2(n.y,n.x))},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var z=function(){function t(t,i,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=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?x.CW:x.CCW,this.angle=l.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var 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 z(s,h,a),m=u.angle.radians()/e;u.orientation===x.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1];t+=this._points[0].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=w;var v=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=v;var d=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){return(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n},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){return(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o},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));return new t(n)},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=d;var g=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,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=g;var R=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var 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=R;var T=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var _=function(){function t(t,i,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=_;var F=function(){function t(){}return t}();F.Color3=[r.Black(),r.Black(),r.Black()],F.Vector2=[o.Zero(),o.Zero(),o.Zero()],F.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],F.Vector4=[s.Zero(),s.Zero(),s.Zero()],F.Quaternion=[a.Zero(),a.Zero()],F.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=F;var M=function(){function t(){}return t}();M.Vector3=[e.Zero()],M.Matrix=[u.Zero(),u.Zero()],M.Quaternion=[a.Zero()]}(BABYLON||(BABYLON={}));";
  60830. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  60831. module.exports = BABYLON;
  60832. };